【问题标题】:How to use xml file as a parameter input for script如何使用xml文件作为脚本的参数输入
【发布时间】:2014-02-04 14:30:16
【问题描述】:

我有一个 PowerShell 脚本,它必须将一个 xml 文件作为脚本中将使用的所有参数/变量的输入源。

我目前如何获得参数 xml 输入代码:

param([xml] $xmlData)

但是当脚本执行时我得到这个错误:

PS> .\script.ps1 -xmlData .\xmlfile.xml
script.ps1 : Cannot process argument transformation on parameter 'xmlData'. Cannot convert
value ".\xmlfile.xml" to type "System.Xml.XmlDocument". Error: "The specified node cannot be inserted as the valid child of this node, because the specified node is the wrong type."
At line:1 char:22
+ .\script.ps1 -xmlData .\xmlfile.xml
+                      ~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [script.ps1], ParameterBindingArgumentTransformationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,script.ps1

在 PS 会话中,如果我这样做,它工作正常,我可以看到从 xml 文件解析的节点和数据,所以我不确定应该如何正确完成,或者我是否遗漏了什么:

PS> $xml = [xml] (gc xmlfile.xml)

PS> $xml.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    XmlDocument                              System.Xml.XmlNode

最后一点,我的 xml 文件确实包含 xml 版本标记,结构很简单:

<root>
<value1>...
<value2>...
   <subnode>...
   <subvalue1>...

我正在跳过结束标签和所有内容。

【问题讨论】:

    标签: xml powershell powershell-3.0


    【解决方案1】:

    根据您的描述,听起来您需要像这样调用脚本:

    .\script.ps1 -xmlData [xml](get-content .\xmlfile.xml)
    

    它将 XML 对象作为输入,而不是文件路径,因此您需要在将其传递给脚本之前进行转换。

    【讨论】:

    • 对我来说,它的工作方式如下 - .\script.ps1 -xmlData ([xml](get-content .\xmlfile.xml))
    【解决方案2】:

    您的脚本需要一个 XML object 作为 xmlData 参数的参数。但是,您将其提供为 XML 文件的 path

    你需要这样调用脚本:

    PS> .\script.ps1 -xmlData [xml](Get-Content .\xmlfile.xml)
    

    在上面的代码中,(Get-Content .\xmlfile.xml) 获取了.\xmlfile.xml 中的文本。 [xml] 然后将该文本转换为 XML 对象,这正是您的脚本所期望的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-15
      • 1970-01-01
      • 2017-12-31
      • 1970-01-01
      • 2016-05-02
      • 2015-07-01
      • 2013-07-10
      • 1970-01-01
      相关资源
      最近更新 更多