我有这个XML
- 我要添加节点的文件" Profile
"在节点内" Profiles
"。
<?xml version="1.0" encoding="utf-8"?>
<Configuration LastWrittenBy="Me">
<Profiles />
<Settings>
<ActiveProfile>None</ActiveProfile>
</Settings>
</Configuration>
以下代码使用PowerShell 3
在我的测试客户端上运行正常。但是当我在其他客户端上使用它时,我无法更新PowerShell (v. 2)
,就会出现问题。
$xmlpath = "C:\Temp\profileSettings.xml"
Load xml-file to an object
$xml = New-Object XML
$xml.Load($xmlpath)
# Create a node
$xmlElt = $xml.Configuration.SelectNodes("Profiles")
$xmlSubElt = $xml.CreateElement("Profile")
$xmlElt.AppendChild($xmlSubElt)
#Save to file
$xml.Save($xmlpath)
我收到此错误消息:
Method invocation failed because [System.Xml.XPathNodeList] doesn't contain a method named 'AppendChild'.
At C:\Temp\Test\test.ps1:10 char:20
+ $xmlElt.AppendChild <<<< ($xmlSubElt)
+ CategoryInfo : InvalidOperation: (AppendChild:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
我确实有另一个运行PowerShell 2
的测试客户端,我更新了该客户端来解决问题。所以我很确定PowerShell
的不同版本让我感到困惑:)(但我可能错了)。我不允许在需要运行具有此功能的脚本的客户端上更新软件。
知道如何解决这个问题吗?非常感谢帮助。
答案 0 :(得分:0)
由于SelectNodes可以返回多个节点,因此您需要在V2上迭代集合,例如尝试:
$xmlElt | Foreach {$_.AppendChild($xmlSubElt)
或者,如果您只期望单个节点使用SelectSingleNode()
。这适用于V3,因为它会在调用属性或方法时自动枚举集合。