Geeks With Blogs

News

qrcode

Lance Robinson

Create Your Badge

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

 Subscribe


Lance's TextBox » About Me » My Resume »Twitter

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 Programming , PowerShell | Back to top


Comments on this post: Pass by Reference Parameters in PowerShell

# re: Pass by Reference Parameters in PowerShell
Requesting 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
Left by guillaume on Jan 21, 2009 4:31 PM

# re: Pass by Reference Parameters in PowerShell
Requesting Gravatar...
Guillaume, thanks for pointing out that oversight on my part! I fixed the code in the example.
Left by Lance on Jan 21, 2009 4:45 PM

# re: Pass by Reference Parameters in PowerShell
Requesting Gravatar...
In powershell comments are prefixed by # and not //

kind regards
Left by fred on Jul 29, 2009 12:51 AM

# re: Pass by Reference Parameters in PowerShell
Requesting Gravatar...
I am searching for some great blog sites for contemplating. I was seeking over web search tools and discovered your blog webpage. Well i like your astounding web journal webpage outline in addition to your posting capacities. Continue doing it.You can free to surf https://rospher.com/
Left by nathandwyer on May 22, 2017 1:25 AM

# re: Pass by Reference Parameters in PowerShell
Requesting Gravatar...
We all have that reference parameters in power shell and we archive many articles. Then you will get surf essay writing reviews and assignments. So we prefer only the following essays and assignments.
Left by inistra on Nov 09, 2017 7:30 AM

Your comment:
 (will show your gravatar)


Copyright © Lance Robinson | Powered by: GeeksWithBlogs.net