[英]I dont get AppendChild to work with PowerShell 2, but with version 3 it works fine
我有這個XML
文件,我想在節點“ Profiles
”內添加節點“ Profile
”。
<?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
會給我帶來麻煩:)(但我可能錯了)。 我不允許在需要使用此功能運行腳本的客戶端上更新軟件。
任何想法如何解決此問題? 非常感謝您的幫助。
由於SelectNodes可以返回多個節點,因此您需要在V2上迭代集合,例如,嘗試:
$xmlElt | Foreach {$_.AppendChild($xmlSubElt)
或者,如果您僅期望一個節點,請使用SelectSingleNode()
。 這在V3上有效,因為調用屬性或方法時它將自動枚舉集合。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.