Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 
like image 728
Denis Avatar asked Aug 26 '11 01:08

Denis


People also ask

How do I get the value of a variable in PowerShell?

The Get-Variable cmdlet gets the PowerShell variables in the current console. You can retrieve just the values of the variables by specifying the ValueOnly parameter, and you can filter the variables returned by name.

How do you pass by reference in PowerShell?

To pass a variable to a parameter that expects a reference, you must type cast your variable as a reference. The brackets and parenthesis are BOTH required.

How do I string a variable in PowerShell?

PowerShell declares a variable by using the $ sign and the variable name. For example, $Services. When we declare any type (Integer, double, string, DateTime) of the variable and when we use them inside the string variable, it automatically converts that variable to the string.

What does $_ do in PowerShell?

The $_ is a variable or also referred to as an operator in PowerShell that is used to retrieve only specific values from the field. It is piped with various cmdlets and used in the “Where” , “Where-Object“, and “ForEach-Object” clauses of the PowerShell.


1 Answers

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.

like image 112
manojlds Avatar answered Oct 25 '22 22:10

manojlds