Why does the Powershell return keyword cause type errors?

$xml = [xml] '<node>foo</node>'
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 function return function

+4
source share
3 answers

Got some confirmation from the PowerShell team on this. This seems to be a bug in the XML adapter. If you look at the object that foo2 pops in the debugger, this is PSObject. If you do not use the return keyword and instead simply output the string "foo2", then the function returns a string object.

XML , PSObject . , PSObject $xml.node, . , , psobject ( [string]):

$xml = [xml] '<node>foo</node>'
function foo2 { return "foo2" }
$xml.node = (foo2).psobject.baseobject
$xml

node
----
foo2
+6

( 1), 0 . , , :

$xml.node = $( myfunc )

, ,

-Oisin

p.s. , , , , , script.

+2

Based on in this article , I would suggest that the compiler decides that it does not know the type of output foo2 is enough to accept, although it is "obvious" that it will always be a string, I assume that there is some code that can add something more to a conclusion that has never been executed ...

Update: Keith Hill answer is correct, not this

0
source

All Articles