How to Share Variables Between Functions in PowerShell?

One PowerShell administrator asked me about sharing variables between functions in PowerShell. There are different methods to do this. In this tutorial, I will show you how to share variables between functions in PowerShell with examples.

To share variables between functions in PowerShell using the global variable method, you can declare a variable with the $global: prefix, making it accessible from anywhere within your script, including inside functions. For example, $global:userCount = 0 initializes a global variable that can be modified by any function, such as AddUser and RemoveUser, ensuring the variable’s value is consistently updated and accessible across different functions.

Share Variables Between Functions in PowerShell

Now, let me show you different methods to share variables between functions in PowerShell.

1. Using Global Variables

One way to share variables between functions in PowerShell is by using global variables. To declare a global variable, you can use the $global: prefix followed by the variable name. Global variables are accessible from anywhere within your PowerShell script, including inside functions.

Here’s an example that demonstrates the usage of global variables:

$global:userCount = 0

function AddUser {
    $global:userCount++
    Write-Host "User added. Total users: $global:userCount"
}

function RemoveUser {
    $global:userCount--
    Write-Host "User removed. Total users: $global:userCount"
}

AddUser
AddUser
RemoveUser

In this example, we declare a global variable $global:userCount to keep track of the number of users. The AddUser and RemoveUser functions modify the global variable, and the changes are reflected throughout the script.

I executed the above PowerShell script, and you can see the output in the screenshot below:

Share Variables Between Functions in PowerShell

2. Passing Variables as Parameters

Now, let me show you another method to share variables between functions.

Another approach to sharing variables between functions is to pass them as parameters. This allows you to specify which variables are being shared explicitly and provides better control over the scope of the variables.

Let me show you a simple example.

function Get-UserName {
    param (
        [string]$userName
    )
    Write-Output "User Name: $userName"
}

function Set-UserName {
    param (
        [string]$newName
    )
    return $newName
}

# Call functions
$userName = "User01"
Get-UserName -userName $userName
$userName = Set-UserName -newName "User02"
Get-UserName -userName $userName

In this example, the Set-UserName function returns a new value, which is then passed to the Get-UserName function.

Here is the output in the screenshot below after I executed the above PowerShell script.

How to Share Variables Between Functions in PowerShell

Let me show you another example.

function CalculateTax($amount, $taxRate) {
    $tax = $amount * $taxRate
    return $tax
}

function ProcessInvoice($invoiceAmount) {
    $salesTaxRate = 0.08
    $stateTaxRate = 0.05

    $salesTax = CalculateTax -amount $invoiceAmount -taxRate $salesTaxRate
    $stateTax = CalculateTax -amount $invoiceAmount -taxRate $stateTaxRate

    $totalTax = $salesTax + $stateTax
    $totalAmount = $invoiceAmount + $totalTax

    Write-Host "Invoice Amount: $invoiceAmount"
    Write-Host "Sales Tax: $salesTax"
    Write-Host "State Tax: $stateTax"
    Write-Host "Total Amount: $totalAmount"
}

ProcessInvoice -invoiceAmount 1000

In this example, the CalculateTax function accepts the $amount and $taxRate parameters and returns the calculated tax. The ProcessInvoice function calls CalculateTax twice, passing the invoice amount and the respective tax rates as arguments. The returned values are then used to calculate the total tax and the total amount.

You can see the output in the screenshot below:

powershell share variables between functions

Check out How to Check if a Variable is Null in PowerShell?

3. Using Script Scope

PowerShell provides a script scope that allows you to share variables between functions within the same script. By setting variables using the script scope in a module, the variables become shareable between the module’s functions.

Variables in the script scope are available to all functions within the script. This method is useful for sharing variables without making them globally accessible.

Let me show you an example.

# Declare a script scope variable
$script:databaseName = "Database01"

function Get-DatabaseName {
    Write-Output "Database Name: $script:databaseName"
}

function Set-DatabaseName {
    param (
        [string]$newName
    )
    $script:databaseName = $newName
}

# Call functions
Get-DatabaseName
Set-DatabaseName -newName "Database02"
Get-DatabaseName

Here, $script:databaseName is shared between the Get-DatabaseName and Set-DatabaseName functions, accessible only within the script.

Here’s another example that explains the usage of script scope:

$script:dbConnection = $null

function ConnectToDatabase {
    $script:dbConnection = New-Object System.Data.SqlClient.SqlConnection("ConnectionString")
    $script:dbConnection.Open()
    Write-Host "Connected to the database"
}

function ExecuteQuery($query) {
    $command = $script:dbConnection.CreateCommand()
    $command.CommandText = $query
    $result = $command.ExecuteReader()
    return $result
}

function DisconnectFromDatabase {
    $script:dbConnection.Close()
    Write-Host "Disconnected from the database"
}

ConnectToDatabase
$data = ExecuteQuery -query "SELECT * FROM Users"
# Process the data...
DisconnectFromDatabase

In this example, we declare a script-scoped variable $script:dbConnection to store the database connection. The ConnectToDatabase function initializes the connection, and the ExecuteQuery function uses the shared connection to execute a query. Finally, the DisconnectFromDatabase function closes the connection.

Read PowerShell Print Variable

4. Using Reference Type Variables

In PowerShell, reference type variables allow a function to change the value of a variable outside its scope. This method is useful when you need a function to modify a variable directly.

Here is an example.

function Increment-Count {
    param (
        [ref]$count
    )
    $count.Value++
}

# Declare a variable
$count = 0

# Call function
Increment-Count -count ([ref]$count)
Write-Output "Count: $count"
Increment-Count -count ([ref]$count)
Write-Output "Count: $count"

In this example, the Increment-Count function uses a reference variable to directly modify the $count variable.

Conclusion

In this tutorial, I have explained how to share variables between functions in PowerShell using different methods, such as global variables, passing variables as parameters, leveraging script scope, etc.

You may like the following tutorials:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

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