Powershell Global Variable: Explained With Examples

by | PowerShell

PowerShell is a versatile scripting language system administrators and developers use to automate tasks and manage system configurations. One important aspect of PowerShell scripting involves the use of variables to store information that can be referenced and manipulated. Global variables hold a significant place among the different types of variables due to their reusability and broad scope.

In PowerShell, global variables are accessible throughout the entire scope of a script or session. They allow data to be shared between different functions or modules. To create a global variable in PowerShell, you can use the “global” keyword at the beginning or the top of a script.

Powershell Global Variable

In this article, we’ll have a detailed discussion on PowerShell global variables. We’ll go over examples and use cases to help you better understand the concept.

Let’s get into it!

Understanding PowerShell Global Variables

Before you start making global variables in PowerShell, let’s quickly review the basics of global variables. You need to have a good understanding of the basics to be able to make valuable variables.

Understanding PowerShell Global Variables

What is a Variable Scope?

In PowerShell, the variable scope is the area where a variable is accessible or visible.

PowerShell protects access to variables, aliases, functions, and PowerShell drives (PSDrives) by limiting their visibility and modification within specific scopes.

What is a Variable Scope

The different PowerShell scopes include:

  • Global: The variable is accessible throughout the entire PowerShell session.
  • Local Scope: The variable is accessible only within the current script or function.
  • Script: The variable is accessible within the current script.
  • Private: The variable is only available within the current parent scope, and it is not inherited by any child scope.

Global vs. Local Variables

A PowerShell global variable is a variable that is accessible across all scripts, functions, or cmdlets within the current session.

To declare a PowerShell global variable, you use the $global: prefix before the variable name.

In the following example, the code creates a global variable named $global:TotalUsers:

$global:TotalUsers = 1000

Local variables are limited to the scope in which they are created. They are only accessible within the current script or function. No prefix is needed to declare a local variable.

For instance:

$totalUsers = 1000

Objects and Types in PowerShell

In PowerShell, variables can store different types of data, such as strings, integers, arrays, functions, and processes.

Objects and Types

The following are some examples of variables with different data types:

  • Strings: A sequence of characters enclosed in single or double quotation marks.$stringVar = "Hello, world!"
  • Integers: Whole numbers, both positive and negative.$intVar = 42
  • Arrays: Collections of objects, where each object can be accessed via an index.$arrayVar = @(1, 2, 3, 4)
  • Functions: Code blocks that perform a specific task and can be called by their name.function Show-Message { param([string]$message) Write-Output $message }
  • Processes: System processes that can be managed using PowerShell cmdlets, such as Get-Process.$processVar = Get-Process -Name powershell

When you’re working with PowerShell global variables, remember that they can store any of these data types. They can be accessible across scripts and functions, making them particularly useful for sharing data throughout a session.

2 Important Global Variable Techniques

In the section above, you learned the basics of a PowerShell Global Variable. We’ll now go over 2 of the most important global variables techniques that you’ll most often use when working with global variables.

3 Important Global Variable Techniques

Specifically, we’ll go over the following:

  1. Set-Variable Cmdlet
  2. Get-Variable Cmdlet

1. Set-Variable Cmdlet

The Set-Variable cmdlet can also be used to create or modify a global variable. Specifying the -Scope parameter as Global sets the variable at the global scope level.

The following PowerShell Script demonstrates this case:

Set-Variable -Name AppVersion -Value "1.0" -Scope Global

This creates a global variable named AppVersion with the value “1.0”.

2. Get-Variable Cmdlet

To retrieve the value of a global variable, you can use the Get-Variable cmdlet. By specifying the -Scope parameter as Global, it retrieves the value of the variable from the global scope.

For example:

Get-Variable -Name AppName -Scope Global

This returns the value of the AppName global variable, which is “MyApp”.

How to Manage PowerShell Global Variables

There are several cmdlets available in PowerShell for you to manage global variables. These are also known as scope modifiers.

How to Manage PowerShell Global Variables

We’ve listed some commonly used ones below:

1. Clear-Variable

This cmdlet clears the value of a variable. To clear a global variable, you can use the -Scope parameter as Global.

Clear-Variable -Name AppName -Scope Global

This clears the value of the AppName global variable.

2. Remove-Variable

This cmdlet removes a variable, effectively deleting it. To remove a global variable, you can use the -Scope parameter as Global.

Remove-Variable -Name AppName -Scope Global

This removes the AppName global variable from the global scope.

3. Remove-Item

This cmdlet can also be used to remove a global variable by specifying the Variable: drive.

Remove-Item -Path Variable:AppName

This removes the AppName global variable.

4. Set-Variable With the -Option parameter

To create a read-only or constant global variable, you can use the -Option parameter with the Set-Variable cmdlet.

Set-Variable -Name ReadOnlyVar -Value "Read Only" -Scope Global -Option ReadOnly

This creates a read-only global variable named ReadOnlyVar with the value “Read Only”.

Best Practices for Using Global Variables in PowerShell

Global variables can be helpful in maintaining state or sharing information across scripts and functions. However, it’s important to use them carefully to avoid unintended consequences.

Best Practices for Using Global Variables

The following are some best practices for using global variables:

  • Minimize the use of global variables: Use global variables only when necessary, and rely more on local or script-scoped variables.
  • Choose descriptive names: Use names that clearly indicate the purpose of the variable and avoid naming conflicts.
  • Initialize your variables: Assign default values to your global variables to avoid accessing uninitialized variables by mistake.
  • Avoid modifying global variables in functions: Modifying global variables within a function can lead to unexpected behavior. Prefer using parameters or return values to pass information between functions.

Advanced Topics and Use Cases With PowerShell Global Variables

We’ll now explore advanced topics and use cases related to PowerShell global variables. We’ll cover the following:

  • Read-Only Global Variables
  • Aliases and Tab-Completion
  • Working with PSDrives
  • Manipulating Hash Tables
Advanced Topics and Use Cases

1. Read-Only Global Variables

PowerShell provides read-only global variables that hold constant values and can be accessed anywhere within your scripts or functions.

They serve as a means to share information throughout the script without the possibility of being modified. Some examples of read-only variables are:

  • $Host: Provides information about the current PowerShell host.
  • $PSHome: The path to the root of the PowerShell installation.

These variables cannot be changed, and if you attempt to do so will result in an error.

2. Aliases and Tab-Completion

PowerShell allows you to create aliases for global variables. This helps streamline your code and improves readability.

To create an alias for a global variable, you can use the Set-Alias command, followed by the desired alias name and the variable name.

For instance:

Set-Alias -Name gvMyVar -Value $global:MyVariable

PowerShell also offers tab completion, which can be used to quickly reference global variables and their aliases.

You can simply type the first few characters of the variable name or alias, then use the tab key to cycle through possible completions.

3. Working With PSDrives

In PowerShell, you can work with global variables as if they are part of a drive called Variable: This is known as a PSDrive.

To access the global variables within the Variable: drive, you can use standard commands such as Get-ChildItem or Set-Location.

The following example will return a list of all the global variables currently available:

Get-ChildItem Variable:\

4. Manipulating Hash Tables

PowerShell’s hash tables can be used as global variables to store and organize data with key-value pairs.

To create a hash table as a global variable, you use the following syntax:

$global:MyHashTable = @{
    Key1 = 'Value1'
    Key2 = 'Value2'
    Key3 = 'Value3'

Hash table global variables allow you to access and manipulate values by their associated keys efficiently.

To add or update a key-value pair, you can use the following syntax:

$global:MyHashTable.Key4 = 'Value4'

To remove a key-value pair from the hash table, you use the Remove method:


Combining hash tables with the global scope functionality allows for efficient data storage and manipulation across your PowerShell scripts and functions.

Frequently Asked Questions

In this section, you’ll find some frequently asked questions that you may have when working with PowerShell global variables.

Frequently Asked Questions

How to declare a PowerShell global variable?

To declare a global variable in PowerShell, you can use the $global: prefix followed by the variable name.

For example:

$global:myVariable = "Hello, world!"

This will create a global variable called myVariable with the value “Hello, world!”.

How to modify global variable value in PowerShell?

You can modify the value of a global variable by using the $global: prefix followed by the variable name and assigning a new value.

For example:

$global:myVariable = "New value"

This will change the value of myVariable to “New value”.

What is variable scope in PowerShell functions?

Variables defined inside a function are local to that function by default, which means they cannot be accessed outside the function.

However, you can use different variable scopes, such as global, script, local, or private, to control the accessibility of a variable. For example:

function Test-Function {
    $local:myLocalVar = "Local variable"
    $script:myScriptVar = "Script variable"

How to access variables outside functions in PowerShell?

To access a variable outside of a function, you can either declare it with the global or script scope or use a return statement to return the value.

For example:

function Get-MyVariable {
    $global:myResult = "Global variable value"
    return $global:myResult

$myVar = Get-MyVariable
Write-Host "Variable value: $myVar"

What is the difference between global and local in PowerShell?

In PowerShell, global variables can be accessed anywhere inside the script, functions, and any cmdlet in the current session.

On the other hand, local variables are limited in scope and can only be accessed within the block in which they are declared (e.g., function, loop, or if statement).

Related Posts