PowerShell: Return values from a function through reference parameters

PowerShell has a special [ref] keyword to specify which parameters are used in a fuction to return values. It's usage is not directly clear however.

If the type of the variable to update is a value type, use the [ref] keyword in the declaration of the function parameter, this specifies that a "pointer" to the variable will be passed.

To pass the "pointer" to the variable, use ([ref]$variable) to create the pointer, and pass this as parameter. To set the value of the value variable pointed to by the "pointer", use the .Value field.

Simple example to show what [ref] does:

C:\Program Files\PowerGUI> $zz = "hoi"
C:\Program Files\PowerGUI> $xz = [ref]$zz
C:\Program Files\PowerGUI> $xz
Value
-----
hoi

C:\Program Files\PowerGUI> $xz.Value = "dag"
C:\Program Files\PowerGUI> $zz
dag 

This is only required for value types, not is the type is a referece type like for example Hashtable.

Some sample code:

function fn
{
param
(
[ref]$arg1,
[ref]$arg2,
$arg3
)

$arg1.Value = 1
$arg2.Value = "overwrite"
$arg3.key = "overwrite hash value"
}

$x = 0
$y = "original"
$z = @{"key" = "original hashvalue"}
$x
$y
$z.key
fn -arg1 ([ref]$x) -arg2 ([ref]$y) -arg3 $z
$x
$y
$z.key

Published Thursday, March 26, 2009 11:41 AM by svdoever
Filed under: ,

Comments

Saturday, March 28, 2009 6:33 PM by Andy

# re: PowerShell: Return values from a function through reference parameters

Thanx ! I enjoyed that ...

$Say = New-Object -Com "SAPI.SpVoice"

Function Say { $Say.speak("$Args")|Out-Null }

1..5| % { $Zz = "Hoi$_"; $Xz = [Ref]$Zz; $Zz; Say "$Zz"; $Xz.Value = "Dag$_"; $Zz; Say "$Zz" }

Thursday, April 30, 2009 5:28 AM by Bob Humber

# re: PowerShell: Return values from a function through reference parameters

I'd trawled a number of sites for infor on Powershell REF parameters, and this is the first clear example!

Tuesday, May 05, 2009 8:35 PM by I Shed T h i r t y P o u n d s in Thirty Days

# re: PowerShell: Return values from a function through reference parameters

Hi, nice post. I have been pondering this topic,so thanks for posting. I will likely be subscribing to your posts. Keep up great writing

Leave a Comment

(required) 
(required) 
(optional)
(required)