In this PowerShell tutorial, I will explain the PowerShell reference variable. First, we will understand what is a reference variable in PowerShell, how to create and use PowerShell reference variables, and how to use a reference variable in functions in PowerShell.
What is a PowerShell Reference Variable?
In programming, a reference variable is a pointer to another variable. It means that instead of holding the actual value, the reference variable holds the address in memory where the value is stored. This is particularly useful when you want to allow a function to modify the actual value of a variable.
PowerShell allows the creation and use of reference type variables through a feature known as ref. By using a reference variable, you can permit a function or cmdlet to change the value of a variable directly.
Create Reference Variables in PowerShell
To create a reference variable in PowerShell, you use the [ref]
type accelerator. Here is a simple example:
# Define a variable with an initial value
$originalValue = "Old Value"
# Create a reference to the variable
$referenceToOriginal = [ref]$originalValue
# Display the value via reference
$referenceToOriginal.Value
In this example, $referenceToOriginal
is a reference to $originalValue
. Any changes made to this reference will affect the $originalValue
variable.
Here you can see the output in the screenshot below:
How to Use PowerShell Reference Variables with Functions
PowerShell Reference variables become particularly useful when passing parameters to functions. By default, when you pass a variable to a function in PowerShell, you are passing a copy of the value (pass by value). However, if you want the function to modify the original variable, you need to pass it by reference.
Let’s look at an example:
function Update-Value {
param ([ref]$data)
$data.Value = "New Value"
}
# Define a variable
$myData = "Initial Value"
# Pass the variable by reference to the function
Update-Value ([ref]$myData)
# Display the updated value
$myData
In this script, the Update-Value
function takes a parameter by reference. Inside the function, we change the value of the parameter using $data.Value
. After the function is called, the original $myData
variable reflects the change.
Here is the output you can see:
When to Use Reference Variables in PowerShell
Reference variables are not commonly used for every scenario. They are best suited for situations where you need to:
- Allow a function to modify one or more variables that are passed to it.
- Work with large data structures that would be inefficient to copy.
- Implement certain data structures or algorithms that require direct manipulation of variable addresses.
PowerShell Pass by Reference
Passing by reference in PowerShell is a concept that allows a function to modify the actual content of a variable, rather than working on a copy of the variable’s value. This is particularly useful when you want to ensure that any changes made to a variable within a function are reflected in the original variable outside the function.
When you pass a variable by reference, you are essentially passing a pointer to the memory location where the data is stored. As a result, if the function modifies the variable, it modifies the variable’s memory content, and the change is visible outside the function as well.
Here’s how you can pass variables by reference in PowerShell:
function Swap-Values ([ref]$first, [ref]$second) {
$temp = $first.Value
$first.Value = $second.Value
$second.Value = $temp
}
# Define two variables
$a = 1
$b = 2
# Pass the variables by reference to the Swap-Values function
Swap-Values ([ref]$a) ([ref]$b)
# Output the results
Write-Host "a is now $a"
Write-Host "b is now $b"
In the Swap-Values
function, we accept two parameters as references. Inside the function, we swap the values using the .Value
property of the reference variables. After calling Swap-Values
, the values of $a
and $b
are swapped, demonstrating that the variables were indeed passed by reference.
It’s important to note that not all PowerShell data types can be passed by reference. Simple data types like integers and strings can be encapsulated in a [ref]
type, whereas complex data types might already be reference types and do not require the [ref]
type to be passed by reference.
Using pass by reference should be done with care, as it can lead to side effects that are harder to track within your scripts. However, when used correctly, it can be a powerful tool for certain tasks, such as updating multiple variables, working with large objects without the performance hit of copying them, or when interfacing with .NET methods that require objects to be passed by reference.
PowerShell reference type is expected in argument
While working with this PowerShell reference type I got the below error:
Calculate : Cannot process argument transformation on parameter ‘number’. Reference type is expected in argument.
At line:6 char:19
Calculate -number [ref]$var
CategoryInfo : InvalidData: (:) [Calculate], ParameterBindingArgumen
tTransformationException
FullyQualifiedErrorId : ParameterArgumentTransformationError,Calculate
And here I was writing the code like below:
Function Calculate([ref]$number)
{
$number.Value = 50
}
$var = 100
Calculate -number [ref]$var
Write-Host $var
The error was because of the way I was passing reference parameters to the function.
Here, we need to add the reference type variable name within the braces (). And When using a [ref] parameter within a function refer to $variable.value. You should call like below:
Calculate -number ([ref]$var)
Conclusion
PowerShell reference variables are powerful and allow you to directly manipulate the value of a variable in memory. This can be particularly useful when you need to ensure that changes made within a function are reflected in the original variable. You can write more efficient and effective PowerShell scripts by understanding how to create and use reference variables.
Here we learned:
- What is a reference variable in PowerShell?
- How to create and use PowerShell reference variable
- PowerShell ref parameter
- PowerShell Reference Variables with Functions
- PowerShell pass by reference
You may also like:
I am Bijay a Microsoft MVP (10 times – My MVP Profile) in SharePoint and have more than 17 years of expertise in SharePoint Online Office 365, SharePoint subscription edition, and SharePoint 2019/2016/2013. Currently working in my own venture TSInfo Technologies a SharePoint development, consulting, and training company. I also run the popular SharePoint website EnjoySharePoint.com
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