25

我是 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
4

1 回答 1

54

您可能会尝试过:

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)

或在like 之外赋值$value = $obj1.value并在字符串中使用。

于 2011-08-26T01:46:53.550 回答