简体   繁体   中英

powershell: how to write-host value from [ref] variable

I'm new to Powershell and I'm trying to work out how to print the value of a [ref] variable from within a function.

Here is my test code:

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"

The output I get from this test is as follows. You'll notice that I don't get the value of $obj1 as I was hoping. I also tried passing in $obj1.value in the call to write-host but that generated the same response.

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

You would have probably tried:

write-host "the new value is $obj1.value"

and got corresponding output of

the new value is System.Management.Automation.PSReference.value

I think you did not notice the .value in the end of the output.

In strings you have to do something like this while accessing properties:

write-host "the new value is $($obj1.value)"

Or use string format, like this:

write-host ("the new value is {0}" -f $obj1.value)

Or assign value outside like $value = $obj1.value and use in string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM