August 13, 2010

How to define a function with ‘ByRef’ arguments ?

In VBscript you can define a function using a ByRef argument like this :

Function CommentLine (ByRef arg)

In PowerShell you have to use the [ref] type to pass the reference of a variable instead of its value.

Here’s a example of how to define and call a function using a [ref] argument :

function CommentLine([ref]$arg) {
	$arg.value = "# " + $arg.value

$Line="This should be a comment"
CommentLine ([ref]$Line)

Don’t forget your passing the reference of the object, you have to use the value property of the reference to access the variable or object itself.


Anonymous said...

What about using 2 parameters?
function CommentLine([ref]$arg, $arg2)

None of the following versions will work:

1. CommentLine ([ref]$line, $line2)
2. CommentLine [ref]$line, $line2

In both cases the output is still "This should be a comment". (Doesn't matter what to do with $arg2 in the function)

ParadisJ said...

Dear Anonymous,

When you pass a parameter as a reference it must be in an expression [between ()].

Here's a version of my function with 2 parameters :

function CommentLine2([ref]$arg, [ref]$arg2) {
$arg.value = "# " + $arg.value
$arg2.value = "# " + $arg2.value

$Line="This should be a comment"
$Line2 = "this is should be a comment too"

Edo Duda said...

Thank you very much! It helps me out a lot. Even I need multi-args function.

Post a Comment