Passing ByRef vs. ByVal

by Apr 27, 2009

Usually, when you assign a variable to another variable, its content is copied. Here is an example:

$a = "Hello"
$b = $a
$a = "Hello World"
$b

As you can see, $b is actually a copy of $a so when you change $a, $b is not changed. If you want to, you can also just pass a pointer to a variable, effectively having two variables use the very same memory to store its values. To pass a pointer, cast to [Ref] like this:

$a = "Hello"
$b = [Ref]$a
$a = "Hello World"
$b

This time, changing $a will also affect $b because both are using the same storage. When you look closely at the result, though, you will notice that $b actually is not a string variable anymore. It is now a PSReference object, and this object has a value property, giving you the actual object content:

$b.Value

Likewise, to change the $a variable through $b, you should assign a new value to the value property found in $b:

$b.Value = "New Text"
$a