Ole*_*sii 2 xml powershell serialization xml-parsing
我正在努力使用PowerShell读取XML文件.
主要思想是 - 我有一个标志,表示是否读取或写入配置文件.如果需要编写文件 - 脚本将获取参数并将其保存到XML文件中.如果该标志设置为"read" - PowerShell脚本不带参数,但它应该从保存的XML中获取它们.
问题是从XML读取.我使用代码写入XML:
$Config = @{}
$Config.parameter1 = $parameterValue
$Config.dictionaryWithArray = $dictWithArray
($Config | ConvertTo-XML).Save("$path")
Run Code Online (Sandbox Code Playgroud)
保存的XML文件结果为:
<?xml version="1.0"?>
<Objects>
<Object Type="System.Collections.Hashtable">
<Property Name="Key" Type="System.String">parameter1</Property>
<Property Name="Value" Type="System.String">value_in_variable_parameter_Value</Property>
<Property Name="Key" Type="System.String">dictionaryWithArray</Property>
<Property Name="Value" Type="System.Collections.Generic.Dictionary`2[System.String,System.String[]]">
<Property Name="Key" Type="System.String">key1</Property>
<Property Name="Value" Type="System.String[]">
<Property Type="System.String">subkey1</Property>
<Property Type="System.String">subvalue1</Property>
</Property>
<Property Name="Key" Type="System.String">key2</Property>
<Property Name="Value" Type="System.String[]">
<Property Type="System.String">subkey2</Property>
<Property Type="System.String">subvalue2</Property>
</Property>
... and so on
Run Code Online (Sandbox Code Playgroud)
我尝试使用诸如http://blogs.technet.com/b/heyscriptingguy/archive/2012/09/13/powertip-use-powershell-to-easily-read-an-xml-document等方法来阅读此配置. aspx,但没有运气.
请问,请问如何读取配置文件,用这种方法编写?或者可能有更好的方法在写入之前序列化配置,所以它会更容易阅读吗?
有很多方法可以使用XML,但您可能已阅读的大多数博客都不会从XML中读取自定义/嵌套对象.我个人并不知道如何做到这一点,但我确信存在解决方案.
或者可能有更好的方法在写入之前序列化配置
这就是我想要关注的答案.你可以使用Export-CliXml
和它的对应物Import-CliXml
.这些cmdlet应该更容易为您完成工作.
#.... your other code that generates $config
$Config | Export-Clixml $path
Run Code Online (Sandbox Code Playgroud)
然后,您可以根据需要调用配置并检查您将数据写入文件之前的值.
$fileConfig = Import-Clixml $path
$fileConfig.parameter1
Run Code Online (Sandbox Code Playgroud)
请注意您的对象可能需要使用-Depth
的复杂程度Export-CliXml
.
-深度
指定XML表示中包含多少级别的包含对象.默认值为2.
归档时间: |
|
查看次数: |
2591 次 |
最近记录: |