如何使用xml文件作为脚本的参数输入

时间:2014-01-15 21:50:33

标签: xml powershell powershell-v3.0

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

我目前如何获得param 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>...

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

2 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:1)

您的脚本期望XML 对象作为xmlData参数的参数。但是,您正在为XML文件提供路径

您需要像这样调用脚本:

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

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