【问题标题】:Writing and reading XML config by PowerShell通过 PowerShell 编写和读取 XML 配置
【发布时间】:2018-02-01 20:36:16
【问题描述】:

我正在努力使用 PowerShell 读取 XML 文件。

主要思想是 - 我有一个标志,指示是读取还是写入配置文件。如果需要写入文件 - 脚本获取参数并将它们保存到 XML 文件。如果标志设置为“读取” - PowerShell 脚本不接受参数,但它应该从保存的 XML 中获取参数。

问题在于从 XML 读取。 我使用代码写入 XML:

$Config = @{}
$Config.parameter1 = $parameterValue
$Config.dictionaryWithArray = $dictWithArray
($Config | ConvertTo-XML).Save("$path")

保存的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

我尝试使用 http://blogs.technet.com/b/heyscriptingguy/archive/2012/09/13/powertip-use-powershell-to-easily-read-an-xml-document.aspx 等方法读取此配置,但没有成功。

您能告诉我如何读取通过这种方法编写的配置文件吗?或者可能有更好的方法在写入之前序列化配置,这样会更容易阅读?

【问题讨论】:

    标签: xml powershell serialization xml-parsing


    【解决方案1】:

    有很多方法可以使用 XML 来做到这一点,但您可能读过的大多数博客都不会从 XML 中读取自定义/嵌套对象。我个人不知道有什么方法可以做到这一点,但我确信存在解决方案。

    或者可能有更好的方法在编写之前序列化配置

    这就是我要重点关注的答案。您可以使用Export-CliXml 及其对应的Import-CliXml。这些 cmdlet 应该更容易为您完成工作。

    #.... your other code that generates $config
    $Config | Export-Clixml $path
    

    然后您可以根据需要调用配置并像在将数据写入文件之前一样检查值。

    $fileConfig = Import-Clixml $path
    $fileConfig.parameter1
    

    警惕您的对象变得多么复杂,因为您可能需要使用-Depth of Export-CliXml

    -深度

    指定在 XML 表示中包含多少级别的包含对象。 默认值为 2

    【讨论】:

    • 实际上这更适合并提供更好的 XML 输出,尽管它不能与字典一起正常运行。不幸的是。
    猜你喜欢
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多