Pass by Reference Parameters in PowerShell

A long time ago Jeffrey Snover briefly mentioned the PowerShell [REF] parameter attribute, but otherwise there isn’t much mention around about how to use it.  It seems simple enough, but I kept getting this error from PowerShell:

“Reference type is expected in argument.”

This post by MOW cleared things up for me – I needed to wrap my [REF] parameters in parens in the function call, like so:

Find-NewMessages $valvar1 ([REF]$refvar1) ([REF]$refvar2)

For those looking to see how pass by reference params are used in the first place, its pretty simple.  Use the [REF] attribute on your function parameters and in your function call, ie:

function Find-NewMessages($valvar1, [REF]$refvar1, [REF]$refvar2) {
  //some stuff
  $refvar1.Value = “hi”
  $refvar2.Value = “bye”
}

$refvar1 = “1”
$refvar2  “2”
Find-NewMessages $valvar1 ([REF]$refvar1) ([REF]$refvar2)
//now $refvar1 = “hi” and $refvar2 = “bye”

Print | posted on Wednesday, January 14, 2009 5:06 PM

Feedback

# re: Pass by Reference Parameters in PowerShell

Left by guillaume at 1/21/2009 4:31 PM
Gravatar I'm sorry to write this, but this code simply does not work :)

You need to use $refvar.Value to make this work !

Guillaume

# re: Pass by Reference Parameters in PowerShell

Left by Lance at 1/21/2009 4:45 PM
Gravatar Guillaume, thanks for pointing out that oversight on my part! I fixed the code in the example.

# re: Pass by Reference Parameters in PowerShell

Left by fred at 7/29/2009 12:51 AM
Gravatar In powershell comments are prefixed by # and not //

kind regards

Your comment:





 
 

Copyright © Lance Robinson

Design by Bartosz Brzezinski

Design by Phil Haack Based On A Design By Bartosz Brzezinski