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”
Technorati Tags: PowerShell, Pass By Reference Parameters