Question:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
$xml = [xml] ' function foo2 { return "foo2" } # all of these fail with the message: # **Cannot set "foo" because only strings can be used as values to set XmlNode properties.** $xml.node = foo2 $xml.node = foo2 -as [string] # because of this issue[1] $xml.node = (foo2) # these work $xml.node = (foo2).tostring() $xml.node = (foo2) -as [string] $xml.node = [string] (foo2) # yet, these two statements return the same value (foo2).gettype() (foo2).tostring().gettype() |
1: PowerShell functions return behavior
Answer:
Got some confirmation from the PowerShell team on this one. This appears to be a bug in the XML adapter. If you look at the object that is spit out by foo2 in a debugger it is a PSObject. If you don’t use the return keyword and instead just output the string “foo2” then the function returns a string object.
The bug in the XML adapter is that it is not unwrapping the PSObject to get at the base object. As a result when it tries to assign the PSObject to $xml.node it fails. For now, as a workaround, you can manually unwrap the psobject like so (or just cast to [string]):
1 2 3 4 5 6 7 8 9 |
$xml = [xml] ' function foo2 { return "foo2" } $xml.node = (foo2).psobject.baseobject $xml node ---- foo2 |