我是 Powershell 新手,我正在尝试弄清楚如何从函数内打印 [ref] 变量的值。
这是我的测试代码:
function testref([ref]$obj1) {
$obj1.value = $obj1.value + 5
write-host "the new value is $obj1"
$obj1 | get-member
}
$foo = 0
"foo starts with $foo"
testref([ref]$foo)
"foo ends with $foo"
我从这个测试中得到的输出如下。您会注意到我没有像我希望的那样获得 $obj1 的值。我还尝试在对 write-host 的调用中传递 $obj1.value ,但这生成了相同的响应。
PS > .\testref.ps1
foo starts with 0
the new value is System.Management.Automation.PSReference
TypeName: System.Management.Automation.PSReference
Name MemberType Definition
---- ---------- ----------
Equals Method bool Equals(System.Object obj)
GetHashCode Method int GetHashCode()
GetType Method type GetType()
ToString Method string ToString()
Value Property System.Object Value {get;set;}
foo ends with 5
您可能会尝试:
write-host "the new value is $obj1.value"
并得到相应的输出
the new value is System.Management.Automation.PSReference.value
我想你没有注意到.value
在输出的末尾。
在字符串中,您必须在访问属性时执行类似的操作:
write-host "the new value is $($obj1.value)"
或者使用字符串格式,如下所示:
write-host ("the new value is {0}" -f $obj1.value)
或者在外部赋值,例如$value = $obj1.value
并在字符串中使用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)