Lance's TextBox

About Me       - Also see my RSS simple services site.

  Home  |   Contact  |   Syndication    |   Login
  510 Posts | 7 Stories | 379 Comments | 258 Trackbacks

News

Lance Robinson is a product manager and software developer in Durham, Chapel Hill, Raleigh, and surrounding areas. More about Lance.

 Subscribe Add to Technorati Favorites

 

 

 

 


 

 

Search My Blog:

 

 

Twitter












Tag Cloud


Archives

Post Categories

Blogs

Miscellanous

Noteworthy Stuff

Popular Posts

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”

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

Feedback

# re: Pass by Reference Parameters in PowerShell 1/21/2009 4:31 PM guillaume
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 1/21/2009 4:45 PM Lance
Guillaume, thanks for pointing out that oversight on my part! I fixed the code in the example.

Post Feedback

Title:
Name:
Email: (never displayed)
Url:
Comments: