2
此代碼:更新數組元素
$test = @"
<Test>
<Child>Hello</Child>
<Child>World</Child>
</Test>
"@
$xml = [xml]$test
$xml.Test.Child[1]
收率:
World
然後,代碼:
$xml.Test.Child[1] = "StackOVerflow"
$xml.InnerXml
收率:
<Test><Child>Hello</Child><Child>World</Child></Test>
爲什麼第二個Child
節點沒有從World
更新爲StackOverflow
?
好吧,讓我們嘗試不同的東西:
$ipaddress=([System.Net.DNS]::GetHostAddresses($hostname)|Where-Object {$_.AddressFamily -eq "InterNetwork"} | select-object IPAddressToString)[0].IPAddressToString
現在我不知道的$ipaddress
是什麼類型:
$ipaddress.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
顯然,這是字符串。
$xml.Test.ChildNodes[1].'#text' = $ipaddress
Cannot set "#text" because only strings can be used as values to set XmlNode properties.
At line:1 char:1
+ $xml.Test.ChildNodes[1].'#text' = $ipaddress
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueException
+ FullyQualifiedErrorId : XmlNodeSetShouldBeAString
但$ipaddress
是字符串!
這最後的工作原理:
$xml.Test.ChildNodes[1].'#text' = [string]$ipaddress
這是怎麼回事?
在PowerShell中相同的行爲6.0.0-alpha.13 –
謝謝你這一點,但你可能已經注意到了,我已經在原始問題本身中發佈了相同的工作。 –