如何使用xml文件作为脚本的参数输入
我有一个PowerShell脚本,它必须将xml文件作为脚本中使用的所有参数/变量的输入源 我当前如何获得param xml输入代码:如何使用xml文件作为脚本的参数输入,xml,powershell,powershell-3.0,Xml,Powershell,Powershell 3.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 "
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>...
...
...
...
...
我跳过了结束标记和所有内容。根据您的描述,听起来您需要这样调用脚本:
.\script.ps1 -xmlData [xml](get-content .\xmlfile.xml)
PS> .\script.ps1 -xmlData [xml](Get-Content .\xmlfile.xml)
它将XML对象导出为输入,而不是文件路径,因此您需要在将其传递到脚本之前进行转换。您的脚本希望XML对象作为
xmlData
参数的参数。但是,您将为它提供XML文件的路径
您需要像这样调用脚本:
.\script.ps1 -xmlData [xml](get-content .\xmlfile.xml)
PS> .\script.ps1 -xmlData [xml](Get-Content .\xmlfile.xml)
在上面的代码中,
(Get Content.\xmlfile.xml)
获取\xmlfile.xml
中的文本<代码>[xml]然后将该文本转换为xml对象,这正是脚本所期望的。对我来说,它的工作方式如下-。\script.ps1-xmlData([xml](获取内容。\xmlfile.xml))