2

This code:

$test = @"
<Test>
  <Child>Hello</Child>
  <Child>World</Child>
</Test>
"@

$xml = [xml]$test
$xml.Test.Child[1]

yields:

World

Then this code:

$xml.Test.Child[1] = "StackOVerflow"
$xml.InnerXml

yields:

<Test><Child>Hello</Child><Child>World</Child></Test>

Why the second Child node is not getting updated from World to StackOverflow?

Okay, let's try something different:

$ipaddress=([System.Net.DNS]::GetHostAddresses($hostname)|Where-Object {$_.AddressFamily -eq "InterNetwork"}   |  select-object IPAddressToString)[0].IPAddressToString

Now I wonder what the type of $ipaddress is:

$ipaddress.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

Apparently it's string.

$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

But $ipaddress is string!

This finally works:

$xml.Test.ChildNodes[1].'#text' = [string]$ipaddress

What's going on?

1 Answer 1

1

Seems to be related to a bug that might have been fixed in PowerShell 6. I don't have a Linux machine at hand to check.

You'll find a description of that bug here.

Meanwhile, there is a workaround, as you have found it:

$test = @"
<Test>
  <Child>Hello</Child>
  <Child>World</Child>
</Test>
"@

$xml = [xml]$test
$xml.Test
$xml.Test.GetType()                 # = XmlElement

$xml.Test.Child[1]                      # = World
$xml.Test.Child[1].GetType()            # = String

$xml.Test.Child[1] = "Tralala"
$xml.Test.Child[1]                      # = World


$xml.Test.ChildNodes.Item(1).GetType()  # = XmlElement
$xml.Test.ChildNodes.Item(1)."#text" = "StackOverflow"
$xml.Test.Child[1]                      # = StackOverflow
Sign up to request clarification or add additional context in comments.

2 Comments

Same behavior on PowerShell 6.0.0-alpha.13
Thank you for this, but as you might have noticed, I've posted the same work around in the original question itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.