PowerShell Reference Variables

While doing a PowerShell technical discussion, someone asked me about PowerShell reference variables. I thought I would write a complete tutorial on how to use reference variables in PowerShell with some examples. Keep reading.

What are Reference Variables in PowerShell?

In PowerShell, variables are represented by text strings that begin with a dollar sign ($). Reference variables, also known as ref variables, are a special type of variable that allows you to pass values by reference instead of by value. This means that when you modify the value of a reference variable, it affects the original variable as well.

Why Use PowerShell Reference Variables?

Reference variables are important when you need to:

  • Pass large objects to functions without copying the entire object.
  • Allow functions to modify the original variable’s value.
  • Optimize memory usage by avoiding unnecessary data duplication.

Create and Use Reference Variables in PowerShell

To create a reference variable in PowerShell, you can use the [ref] type accelerator. Here’s an example:

$originalVariable = 10
$refVariable = [ref]$originalVariable
$refVariable

In this example, we first create a regular variable $originalVariable and assign it a value of 10. Then, we create a reference variable $refVariable by using the [ref] type accelerator and assigning it the value of $originalVariable.

You can see the output in the screenshot below:

Reference Variables in PowerShell

Modify PowerShell Reference Variables

Now, let’s see how modifying a reference variable affects the original variable. Consider the following example:

$originalVariable = 10
$refVariable = [ref]$originalVariable

$refVariable.Value = 20

Write-Host "Original Variable: $originalVariable"
Write-Host "Reference Variable: $($refVariable.Value)"

In this example, we modify the value of $refVariable by assigning it a new value of 20. When we output the values of both variables, we see that modifying $refVariable also changed the value of $originalVariable:

Original Variable: 20
Reference Variable: 20

This explains the power of reference variables in PowerShell. When you modify a reference variable, it directly affects the original variable it references.

You can see the output in the screenshot below after I executed the above PowerShell script.

PowerShell Reference Variables

Access Reference Variables Outside Functions

In PowerShell, variables have different scopes that determine where they can be accessed from. By default, variables created within a function are only accessible within that function’s scope. However, you can use reference variables to access and modify variables outside of a function.

To access a variable outside of a function, you can either declare it with the global or script scope modifier. Here’s an example:

$global:externalVariable = 10

function Update-ExternalVariable([ref]$refVariable) {
    $refVariable.Value = 20
}

Update-ExternalVariable([ref]$global:externalVariable)

Write-Host "External Variable: $externalVariable"

In this example, we declare a global variable $global:externalVariable and assign it a value of 10. We then define a function Update-ExternalVariable that takes a reference variable $refVariable as a parameter. Inside the function, we modify the value of the reference variable to 20.

Next, we call the Update-ExternalVariable function, passing the $global:externalVariable as a reference using the [ref] type accelerator. Finally, we output the value of $externalVariable, which has been modified by the function:

External Variable: 20

By using the global scope modifier, we ensure that the variable is accessible both inside and outside the function.

You can also see the output in the screenshot below:

Access Reference Variables Outside Functions

PowerShell Reference Variables in Strings

In PowerShell, you can include variables directly within strings using variable substitution or string interpolation. This allows you to embed variable values into strings without explicit concatenation.

To include a reference variable in a string, you can use the variable name within the string enclosed in curly braces {}. Here’s an example:

$originalVariable = 10
$refVariable = [ref]$originalVariable

$message = "The value of the reference variable is: $($refVariable.Value)"
Write-Host $message

In this example, we create a regular variable $originalVariable and a reference variable $refVariable that refers to $originalVariable. We then define a string $message that includes the value of the reference variable using the syntax {$refVariable.Value}.

When we output the $message string, it will display the value of the reference variable:

The value of the reference variable is: 10

Note that we use the .Value property to access the value of the reference variable within the string.

You can also see the exact output in the screenshot below:

PowerShell Reference Variables in Strings

PowerShell Reference Variable Examples

Let me show you how to create and use reference variables with examples.

Example 1: Modifying Configuration Settings

Suppose you have a PowerShell script that reads configuration settings from a file and allows the user to modify them. You can use reference variables to directly update the configuration values. Here’s an example:

$config = @{
    LogLevel = "Info"
    MaxRetries = 3
    Timeout = 30
}

function Update-Config([ref]$configRef) {
    $configRef.Value.LogLevel = "Debug"
    $configRef.Value.MaxRetries = 5
    $configRef.Value.Timeout = 60
}

Update-Config([ref]$config)

Write-Host "Updated Configuration:"
$config

In this example, we define a $config hashtable that represents the configuration settings. We then create a function Update-Config that takes a reference variable $configRef as a parameter.

Inside the function, we modify the values of the configuration settings using the reference variable. Finally, we call the Update-Config function, passing the $config variable as a reference.

The output shows the updated configuration values in the screenshot below:

PowerShell Reference Variable Examples

Example 2: Passing Variables to Functions

Reference variables are particularly useful when you must pass variables to PowerShell functions and have the function modify their values. Consider the following example:

function Calculate-Sum([ref]$result, $a, $b) {
    $result.Value = $a + $b
}

$sum = 0
Calculate-Sum([ref]$sum, 10, 20)
Write-Host "Sum: $sum"

In this example, we define a function Calculate-Sum that takes a reference variable $result and two regular variables $a and $b. Inside the function, we calculate the sum of $a and $b and assign the result to the $result reference variable. We then call the Calculate-Sum function, passing the $sum variable as a reference along with the values 10 and 20. The output shows the calculated sum:

Sum: 30

By using a reference variable, we can modify the value of $sum inside the function and have the change reflected outside the function.

Conclusion

PowerShell reference variables allow data manipulation by directly referencing the original variables or objects. This optimizes memory usage and simplifies the process of passing and modifying data within functions. I hope now you know how to use reference variables in PowerShell.

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.