PowerShell Global Variables [With Examples]

As a PowerShell expert, I often need to manage and manipulate variables across various scripts and functions. One powerful feature of PowerShell is the ability to create global variables. In this tutorial, I’ll explain everything about PowerShell global variables and how to use them and provide some practical examples.

PowerShell global variables are variables that are accessible from any scope within the current session, allowing for data sharing across scripts, functions, and cmdlets. Declared using the $global: prefix, these variables are ideal for storing information like API keys or configuration settings that need to be consistently accessed throughout your code. For example, $global:ApiKey = "your_api_key_here" can be used in multiple functions to interact with APIs without hardcoding the key repeatedly.

What is a Global Variable in PowerShell?

In PowerShell, a global variable is a variable that is accessible from any scope within the current session. This means that once you define a global variable, it can be used by any script, function, or cmdlet running in that session. This is extremely useful for storing information that needs to be shared across different parts of your code.

Syntax to Declare Global Variables in PowerShell

To declare a global variable in PowerShell, you use the $global: prefix followed by the variable name. Here’s the basic syntax:

$global:VariableName = "Value"

For example, if you want to create a global variable to store the name of a city, you could write:

$global:City = "New York"

Read PowerShell Local Variables

PowerShell Global Variable in Function

In PowerShell, a global variable can be accessed inside a function using the $global: prefix. This allows the function to read or modify the value of the global variable.

Example

Here is an example:

$global:Message = "Hello, World!"

function Show-Message {
    Write-Output $global:Message
}

Show-Message  # Output: Hello, World!

In this example, the global variable $global:Message is accessed inside the Show-Message function to output its value.

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

powershell global variable

PowerShell Create Global Variable Inside Function

You can create a global variable inside a function by using the $global: prefix when you declare the variable. This makes the variable accessible globally, even outside the function.

Example

Here is an example to create a global variable inside a function in PowerShell.

function Create-GlobalVariable {
    $global:Greeting = "Welcome to PowerShell!"
}

Create-GlobalVariable
Write-Output $global:Greeting  # Output: Welcome to PowerShell!

Here, the function Create-GlobalVariable creates a global variable $global:Greeting, which can then be accessed outside the function.

Here is the output in the screenshot below:

PowerShell Create Global Variable Inside Function

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

Set Global Variable in Function in PowerShell

Setting a global variable inside a function involves using the $global: prefix to ensure that the variable’s value is modified globally.

Let me show you an example of how to set global variables in a function in PowerShell.

Example

$global:Counter = 10

function Set-GlobalCounter {
    $global:Counter = 20
}

Set-GlobalCounter
Write-Output $global:Counter  # Output: 20

In this example, the Set-GlobalCounter function sets the value of the global variable $global:Counter to 20.

Check out PowerShell Variable Naming Conventions

Change Global Variable Inside a PowerShell Function

Changing a global variable inside a function in PowerShell means updating its value using the $global: prefix. This ensures that the change is reflected globally across the entire session.

Here is an example.

Example

$global:Status = "Inactive"

function Activate-Status {
    $global:Status = "Active"
}

Activate-Status
Write-Output $global:Status  # Output: Active

In this example, the Activate-Status function changes the value of the global variable $global:Status from “Inactive” to “Active”.

The output is in the screenshot below. I executed the above code using VS code.

Change Global Variable Inside a PowerShell Function

PowerShell Global Variable Examples

Let me show you some practical examples to help you understand how global variables in PowerShell.

Example 1: Store API Keys

Suppose you are working on a script that interacts with the U.S. Census Bureau’s API to fetch population data. You can store the API key as a global variable so that it can be accessed from multiple functions within your script.

$global:ApiKey = "your_api_key_here"

function Get-PopulationData {
    param (
        [string]$State
    )
    $url = "https://api.census.gov/data/2020/dec/sf1?get=NAME&for=state:$State&key=$global:ApiKey"
    $response = Invoke-RestMethod -Uri $url
    return $response
}

# Fetch population data for California
$populationData = Get-PopulationData -State "06"
Write-Output $populationData

In this example, the $global:ApiKey variable is accessible within the Get-PopulationData function, making it easy to reuse the API key without hardcoding it multiple times.

Example 2: Configure Environment Settings

Suppose you are setting up a script to configure multiple servers in different states. You can store configuration settings that apply to all servers in global variables.

$global:ServerLocation = "USA"
$global:TimeZone = "Eastern Standard Time"

function Configure-Server {
    param (
        [string]$ServerName
    )
    Write-Output "Configuring $ServerName located in $global:ServerLocation with timezone $global:TimeZone"
    # Additional configuration logic here
}

# Configure servers
Configure-Server -ServerName "Server1"
Configure-Server -ServerName "Server2"

Here, the $global:ServerLocation and $global:TimeZone variables are used to store configuration settings that apply to all servers, ensuring consistency across the script.

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

PowerShell Global Variable Examples

Best Practices for Using Global Variables in PowerShell

While global variables can be incredibly useful, it’s important to use them carefully to avoid potential issues such as variable name conflicts. Here are some best practices to follow:

  1. Naming Conventions: Use clear and descriptive names for global variables to avoid conflicts and make your code more readable.
  2. Documentation: Document the purpose of each global variable, especially in larger scripts, to help other developers understand their usage.
  3. Scope Management: Limit the use of global variables to scenarios where they are truly necessary. Consider using other scopes like script or local when appropriate.

Conclusion

Global variables in PowerShell help you share data across different parts of your script, making your code more modular and maintainable. In this tutorial, I explain how to declare and use global variables in PowerShell and also show some examples related to PowerShell global variables. If you still have any questions, feel free to leave a comment below.

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

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