为什么Powershell的"return"关键字会导致类型错误?

Ric*_*erg 4 powershell

$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()
Run Code Online (Sandbox Code Playgroud)

1:PowerShell函数返回行为

Kei*_*ill 6

得到PowerShell团队的一些确认.这似乎是XML适配器中的错误.如果你在调试器中查看由foo2吐出的对象,它就是一个PSObject.如果不使用return关键字而只输出字符串"foo2",则函数返回一个字符串对象.

XML适配器中的错误是它不会解包PSObject以获取基础对象.因此,当它尝试将PSObject分配给$ xml.node时,它将失败.现在,作为一种解决方法,您可以像这样手动解包psobject(或者只是转换为[string]):

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

node
----
foo2
Run Code Online (Sandbox Code Playgroud)