Search notes:

PowerShell: Pass function/cmdlet parameters by reference

Integral types

«Integral types» are passed by value by default.
In order to pass such parameter to a function or cmdLet by reference, the parameter needs to be declared as a System.Management.Automation.PSReference type.
This type can be abbreviated with the type accelerator [ref].

Function-parameter definition

Optionally, the expected type of the parameter can be specified after [ref], for example [ref][string] as shown in the following simple function declaration.
The value of the parameter that needs to be returned to the caller can then be assigned to the parameter's property .value:
function demonstrate-passing-by-reference {
   param (
      [ref][string] $result
   )

   $result.value = 'value assigned in function'
}

Calling the function

When calling the function, the variable that receives the out value also needs to be declared with the [ref] type accelerator and enclosed in parantheses, as shown below:
[string] $xyz = ''

demonstrate-passing-by-reference ([ref] $xyz)

write-host "xyz after calling function: $xyz"

Object types

Object types (such as a psObject or a hash table) are passed by reference by default:
function change-values {
   param (
      $p
   )

   $p.txt = 'changed'
   $p.num =  99
}

$hash =                               @{num = 42; txt = 'Hello world'}
$obj  = new-object psObject -property @{num = 42; txt = 'Hello world'}

change-values $hash
change-values $obj

write-host "num = $($hash.num), txt = $($hash.txt)"
write-host "num = $($obj.num ), txt = $($obj.txt )"
Github repository about-PowerShell, path: /language/function/parameter/pass-by-reference/object.ps1

Index