Reference Variables in PowerShell

Are you looking to learn how to manipulate variables more dynamically in PowerShell? The answer is the PowerShell reference variables.

I’ve used this many times as a PowerShell developer with years of experience. Let me explain how to use reference variables in PowerShell with some examples.

What Are PowerShell Reference Variables?

In PowerShell, variables typically store values directly. For example, when you create a variable $name = “John”, the variable $name contains the value “John”. However, reference variables work differently – they point to the memory location of another variable rather than storing the value itself.

A Reference Variable in PowerShell allows you to pass variables by reference rather than by value. This means that when you pass a variable to a function or another scope, the original variable can be modified directly.

Syntax of PowerShell Reference Variables

Let me show you a simple example of PowerShell reference variables.

To create and use a reference variable in PowerShell, use the [ref] type accelerator.

Here is the complete PowerShell script:

Function Add-Ten {
    param([ref]$number)
    $number.Value += 10
}

$num = 5
Add-Ten -number ([ref]$num)
Write-Host "Updated value: $num"  # Outputs: Updated value: 15

In the example above:

  • [ref]$number indicates a reference parameter.
  • $number.Value accesses and modifies the actual value.

You can see the exact output in the screenshot below; I executed the above script using VS Code.

powershell reference variable

Check out PowerShell Global Variables

Create Reference Variables in PowerShell

Now, let’s explore how to create reference variables in PowerShell. There are several methods you can use; I will show you two methods here:

Method 1: Using [ref] Parameter

The best way to create a reference variable is by using the [ref] type accelerator:

$originalValue = 10
$referenceValue = [ref]$originalValue

# Access the value using the .Value property
Write-Output "Original value: $originalValue"
Write-Output "Reference value: $($referenceValue.Value)"

# Change the value through the reference
$referenceValue.Value = 20

# Both variables reflect the change
Write-Output "Updated original value: $originalValue" 
Write-Output "Updated reference value: $($referenceValue.Value)"

In this example, when we modify $referenceValue.Value, we’re actually changing the value stored in $originalValue.

Here is the exact output in the screenshot below:

powershell pass by reference

Read Check if a Variable is Null or Empty in PowerShell

Method 2: Using Get-Variable and Set-Variable

Another approach is to use the Get-Variable and Set-Variable cmdlets to create a reference variable in PowerShell:

$myVariable = "Hello World"

# Get a reference to the variable
$reference = Get-Variable -Name myVariable

# Display and modify through the reference
Write-Output "Original: $($reference.Value)"
$reference.Value = "Updated Value"
Write-Output "After update: $myVariable"

This method is particularly useful when you need to work with variables where you only know their names as strings.

Check out Set Environment Variables Using PowerShell

Pass Reference Variable to a Function in PowerShell

One of the most powerful uses of reference variables is passing them to functions. Let me show you an example.

function Update-Value {
    param(
        [ref]$Parameter
    )
    # Modify the value
    $Parameter.Value = $Parameter.Value * 2
}

$myNumber = 5
Write-Output "Before function: $myNumber"
Update-Value -Parameter ([ref]$myNumber)
Write-Output "After function: $myNumber"  # Will display 10

This technique allows functions to modify variables from the caller’s scope – something that’s not normally possible with PowerShell’s default pass-by-value behavior.

You can see the exact output in the screenshot below:

Pass Reference Variable to a Function in PowerShell

Read PowerShell Variable Naming Conventions

Return Multiple Values from a Function Using Reference Variables in PowerShell

Now, let me show you another real use of a reference variable in PowerShell.

PowerShell doesn’t support returning multiple values natively, but reference variables are a neat workaround. Here is an example and the complete PowerShell script.

Function Get-MathOperations {
    param(
        [int]$a,
        [int]$b,
        [ref]$sum,
        [ref]$difference
    )
    $sum.Value = $a + $b
    $difference.Value = $a - $b
}

$sumResult = 0
$diffResult = 0

Get-MathOperations -a 10 -b 4 -sum ([ref]$sumResult) -difference ([ref]$diffResult)

Write-Host "Sum: $sumResult"        # Outputs: Sum: 14
Write-Host "Difference: $diffResult" # Outputs: Difference: 6

You can see the exact output in the screenshot below:

Return Multiple Values from a Function Using Reference Variables in PowerShell

Here is another example of a function returning multiple values using a PowerShell reference variable.

function Get-FileStats {
    param(
        [string]$Path,
        [ref]$LineCount,
        [ref]$WordCount,
        [ref]$CharCount
    )
    
    $content = Get-Content -Path $Path
    $LineCount.Value = $content.Count
    $WordCount.Value = ($content | Measure-Object -Word).Words
    $CharCount.Value = ($content | Measure-Object -Character).Characters
}

$lines = 0
$words = 0
$chars = 0

Get-FileStats -Path "C:\MyFile.txt" -LineCount ([ref]$lines) -WordCount ([ref]$words) -CharCount ([ref]$chars)

Write-Output "Lines: $lines"
Write-Output "Words: $words"
Write-Output "Characters: $chars"

Check out PowerShell Array of Strings

Working with Complex Objects by Reference in PowerShell

Let me show you another use of a PowerShell reference variable.

Reference variables are particularly valuable when working with complex objects.

Here is an example.

$employee = @{
    Name = "James Wilson"
    Department = "IT"
    Salary = 75000
}

function Give-Promotion {
    param(
        [ref]$EmployeeRecord
    )
    
    $currentEmployee = $EmployeeRecord.Value
    $currentEmployee.Salary += 5000
    $currentEmployee.Title = "Senior " + ($currentEmployee.Title ? $currentEmployee.Title : $currentEmployee.Department)
    
    # The original object is updated
}

Give-Promotion -EmployeeRecord ([ref]$employee)
Write-Output "Employee after promotion:"
$employee | Format-Table -AutoSize

Here is the exact output in the screenshot below:

Working with Complex Objects by Reference in PowerShell

When to Use Reference Variables in PowerShell

Here is a summary of when to use reference variables in PowerShell. This will help decide if you need [ref] variables:

Use CaseUse [ref]?Alternative
Modify the variable inside a function✅ YesN/A
Return multiple values✅ YesCreate and return a hashtable/object
Work with large data structures✅ YesConsider performance trade-offs
Read-only access❌ NoPass by value (default PowerShell way)

In this tutorial, I explained how to create and manipulate reference variables in PowerShell with examples.

We also saw a few advanced uses of PowerShell reference variables, such as:

  • Pass a reference variable to a function in PowerShell
  • Return multiple values from a function using PowerShell
  • How to work with complex objects by reference in PowerShell

I know this is a little advanced concept, but I hope you can now use it.

You may also like:

1 thought on “Reference Variables in PowerShell”

  1. This article is influenced by how to do things via c# but lacks of fundamentals regarding PowerShell. Firstly, that’s not the correct way to set a script-level variable. You should simply use PowerShell-way: $script:number. Secondly, this approach is not recommended for writing any kind of PowerShell code, as it is prone to mistakes. Lastly, the function names are a mess as they don’t use verb-noun format and they don’t actually do what they are called. A much better approach would be:
    1) You aren’t doing any calculations via Calculate function
    function Set-ValueTo50
    {
    50
    }
    $num = Set-ValueTo50
    $num

    2.1) Not optimal
    function Set-BhawanaRathore
    {
    $script:FirstName = “Bhawana”
    $script:LastName = “Rathore”
    }

    $FirstName = “Bijay”
    $LastName = “Sahoo”
    Write-Host “$FirstName $LastName”
    Set-BhawanaRathore $FirstName $LastName
    Write-Host $firstname” “$lastname

    2.2) Optimized
    function Set-FirstNameBhawana
    {
    “Bhawana”
    }
    function Set-LastNameRathore
    {
    “Rathore”
    }

    $FirstName = “Bijay”
    $LastName = “Sahoo”
    Write-Host “$FirstName $LastName”
    $FirstName = Set-FirstNameBhawana
    $LastName = Set-LastNameRathore
    Write-Host $firstname” “$lastname

Leave a Comment

Power Apps functions free pdf

30 Power Apps Functions

This free guide walks you through the 30 most-used Power Apps functions with real business examples, exact syntax, and results you can see.

Download User registration canvas app

DOWNLOAD USER REGISTRATION POWER APPS CANVAS APP

Download a fully functional Power Apps Canvas App (with Power Automate): User Registration App