我有一个 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 session 中,如果我这样做,它工作正常,我可以看到从 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)
它期望 XML 对象作为输入,而不是文件路径,因此您需要在将其传递给脚本之前进行转换。
关于xml - 如何使用xml文件作为脚本的参数输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21148982/