Powershell – Pass Value By Reference

Background

Wanted to provide a quick example on how to pass by Reference in Powershell.

Outline

  1. Function
    • Function Definition
      • Parameter Block
        • Type is Ref ( System.Management.Automation.PSReference )
    • Function Module
      • To change the value of the parameter
      • Reference the value property
        • Example => var.value
  2. Calling Module
    • Cast the variable as a ref
      • Example => ( [ref]  ( var1) )

Code

Script


Set-StrictMode -Version 1.0

function swapByValue( `
                          $number1 `
                        , $number2 `
                    )
{

    [object] $_holding=0;

    $_holding = $number1;

    $number1 = $number2;

    $number2 = $_holding; 

}               

function swapByRef( `
                      [ref] $number1 `
                    , [ref] $number2 `
                  )
{

    [object] $_holding=0;

    #Get value of reference/pointer passed in
    $_holding = $number1.Value;

    #Set value of reference/pointer passed in
    $number1.value = $number2.Value;

    #Set value of reference/pointer passed in
    $number2.value = $_holding; 

}               

[int] $number1=10;
[int] $number2=20;

[string] $log=""
[string] $formatLog="State {0} => Number 1 is {1} and Number 2 is {2} `r`n"

Write-Host

$log = $formatLog -f "Initial", $number1, $number2;
Write-Host $log -ForegroundColor blue

$null = swapByValue $number1 $number2

$log = $formatLog -f "Post swap", $number1, $number2;
Write-Host $log -ForegroundColor red

$null = swapByRef ([ref] $number1) ([ref] $number2)

$log = $formatLog -f "Post swapByRef", $number1, $number2;
Write-Host $log -ForegroundColor green

Output

Text

>powershell ./swapInt.ps1

State Initial => Number 1 is 10 and Number 2 is 20

State Post swapInt => Number 1 is 10 and Number 2 is 20

State Post swapIntByRef => Number 1 is 20 and Number 2 is 10

Image

passByReference.output.20200208.0912PM

 

References

  1. Microsoft
    • PowerShell

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s