Den*_*nis 17 powershell function ref
我是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"
Run Code Online (Sandbox Code Playgroud)
我从这个测试得到的输出如下.你会注意到我没有像我希望的那样得到$ obj1的值.我也试过在写入主机的调用中传入$ 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
Run Code Online (Sandbox Code Playgroud)
man*_*lds 39
你可能会尝试过:
write-host "the new value is $obj1.value"
Run Code Online (Sandbox Code Playgroud)
得到了相应的输出
the new value is System.Management.Automation.PSReference.value
Run Code Online (Sandbox Code Playgroud)
我认为你没有注意到.value输出的结尾.
在字符串中,您必须在访问属性时执行以下操作:
write-host "the new value is $($obj1.value)"
Run Code Online (Sandbox Code Playgroud)
或者使用字符串格式,如下所示:
write-host ("the new value is {0}" -f $obj1.value)
Run Code Online (Sandbox Code Playgroud)
或者在value之外指定值$value = $obj1.value并在string中使用.
| 归档时间: |
|
| 查看次数: |
51838 次 |
| 最近记录: |