As a PowerShell developer, I often got scenarios where using global variables can greatly simplify code and make it more maintainable. In this tutorial, I will explain how to create and use PowerShell global variables with examples.
PowerShell Variable Scope
Before understanding a global variable in PowerShell, let me explain the concept of variable scope in PowerShell. PowerShell has three main scopes: local, script, and global.
- Local Scope: Variables defined within a function or a script block are considered local and are only accessible within that specific context.
- Script Scope: Variables defined at the top level of a script are considered script-scoped and are accessible throughout the entire script, including inside functions.
- Global Scope: Variables defined with the
$global:prefix are considered global and are accessible across all scripts, functions, or cmdlets within the current PowerShell session.
Create and Use Global Variables in PowerShell
To create a global variable in PowerShell, simply prefix the variable name with $global:. Here’s an example:
$global:userCount = 100
Now, the $userCount variable is accessible from anywhere within the current PowerShell session. You can access and modify its value from any script, function, or cmdlet.
Let me show you a real example now.
Suppose you’re managing a large Active Directory environment of a company and need to store the domain controller’s hostname for use across multiple scripts. You can define a global variable like this:
$global:domainController = "dc1.example.com"
Now, any script or function can access the $domainController variable without the need to pass it as a parameter or redefine it.
Check out PowerShell Get-Date Format
PowerShell Set Global Variable
To set a global variable in PowerShell, you can use the $global: prefix followed by the variable name. This ensures that the variable is accessible from anywhere within the current PowerShell session. Here’s an example:
$global:maxUsers = 1000
In this example, we define a global variable named $maxUsers and assign it a value of 1000. Now, this variable can be accessed and modified from any script, function, or cmdlet within the same PowerShell session.
Let’s consider another example. Suppose you want to store the path to a common log file directory:
$global:logFilePath = "C:\Logs\MyApplication"
Now, any script or function can access the $logFilePath variable to read or write log files without the need to redefine the path.
Check out PowerShell try catch with examples
Modify A Global Variable in PowerShell
Global variables can be modified from any scope, making them a powerful tool for sharing data between scripts and functions. Here’s an example that explains modifying a global variable:
$global:userCount = 100
function UpdateUserCount {
$global:userCount += 50
}
Write-Host "Initial User Count: $global:userCount"
UpdateUserCount
Write-Host "Updated User Count: $global:userCount"
Output:
Initial User Count: 100
Updated User Count: 150
In this example, the UpdateUserCount function increments the $global:userCount variable by 50, and the changes are reflected outside the function.
I executed the above PowerShell script using VS code, and you can see the exact output in the screenshot below:

Check out PowerShell Function With Parameters
How to Use Global Variable in Function in PowerShell
To use a global variable inside a PowerShell function, you can directly access it using the $global: prefix. This allows you to read or modify the value of the global variable within the function. Here’s an example:
function GetUserCount {
$count = Get-ADUser -Filter * | Measure-Object | Select-Object -ExpandProperty Count
$global:maxUsers = $count
}
In this example, the GetUserCount function retrieves the total number of users in Active Directory and assigns the value to the $global:maxUsers variable. By using the $global: prefix, we ensure that the global variable is modified within the function.
Let’s consider another example. Suppose you have a function that logs messages to a file using the global $logFilePath variable:
function LogMessage {
param($message)
$timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$logEntry = "$timestamp - $message"
Add-Content -Path $global:logFilePath -Value $logEntry
}
In this example, the LogMessage function takes a $message parameter and appends it to the log file specified by the $global:logFilePath variable. By using the global variable directly within the function, we can access its value without the need to pass it as a parameter.
You can then use the LogMessage function from anywhere in your PowerShell scripts or modules:
LogMessage -message "Application started"
# Perform some operations
LogMessage -message "Application completed successfully"
These log messages will be appended to the file specified by the $global:logFilePath variable.
Read PowerShell Variable Naming Conventions
PowerShell Global Variable Example
Now, let me show you an example of a PowerShell global variable that I recently worked on with one of my clients.
Let’s consider a real-world example of managing Office 365 licenses for a company in the USA.
Suppose you have a set of PowerShell scripts that perform various tasks related to Office 365 license management, such as assigning licenses, generating reports, and sending notifications. You can define global variables to store common configuration settings and data:
$global:o365AdminUser = "admin@example.com"
$global:o365AdminPassword = ConvertTo-SecureString "P@ssw0rd" -AsPlainText -Force
$global:o365TenantId = "abc123def456"
$global:licenseThreshold = 100
These global variables can be accessed and used across multiple scripts and functions. For example:
function AssignLicense {
param($user)
$credential = New-Object System.Management.Automation.PSCredential ($global:o365AdminUser, $global:o365AdminPassword)
Connect-MsolService -Credential $credential -TenantId $global:o365TenantId
Set-MsolUserLicense -UserPrincipalName $user -AddLicenses "example:ENTERPRISEPACK"
}
function GenerateReport {
$licensedUsers = Get-MsolUser -All | Where-Object {$_.IsLicensed -eq $true}
$licenseCount = $licensedUsers.Count
if ($licenseCount -gt $global:licenseThreshold) {
Send-MailMessage -To "admin@example.com" -Subject "License Threshold Exceeded" -Body "Current license count: $licenseCount"
}
}
In this example, the AssignLicense function uses the $global:o365AdminUser, $global:o365AdminPassword, and $global:o365TenantId variables to connect to the Office 365 tenant and assign a license to a user. The GenerateReport function uses the $global:licenseThreshold variable to determine if the license count exceeds a specified threshold and sends a notification email accordingly.
Check out PowerShell Reference Variable
Best Practices for Using Global Variables in PowerShell
Though global variables are very much useful in PowerShell, you should follow some best practices while using a global variable in PowerShell. Here are some best practices and considerations:
- Use meaningful and descriptive names for global variables to improve code readability and maintainability.
- Avoid using too many global variables, making your code harder to understand and debug.
- Consider using configuration files or environment variables to store global settings instead of relying solely on global variables.
- Be cautious when modifying global variables from multiple scripts or functions, as it can lead to unexpected behavior if handled improperly.
Conclusion
You can use the PowerShell global variables to share data and configuration settings across scripts, functions, and modules. In this tutorial, I explained everything about the variable scopes, creating and modifying global variables, and various PowerShell global variable examples.
You may also like the following tutorials:
- Download a File from URL Using PowerShell
- How to Create a Folder If Not Exists in PowerShell?
- How to Add Quotes in PowerShell?
- How to Create a File in PowerShell if it Doesn’t Exist?

Hey! I’m Bijay Kumar, founder of SPGuides.com and a Microsoft Business Applications MVP (Power Automate, Power Apps). I launched this site in 2020 because I truly enjoy working with SharePoint, Power Platform, and SharePoint Framework (SPFx), and wanted to share that passion through step-by-step tutorials, guides, and training videos. My mission is to help you learn these technologies so you can utilize SharePoint, enhance productivity, and potentially build business solutions along the way.
Hey Bijay this helped me alot but I wanted to show you and anyone else something as the default answer on Google. If you don’t want to set things explicetly ‘everywhere’, you can set it in the function access it from $global.
Eg:
$Changed = $False;
Write-Host “Changed is Defaulted to:” $Changed
function calculateValue ()
{
$global:Changed = $True;
}
Write-Host “Changed is unaffected by a function that has not been called yet:” $Changed
$Changed = $False;
Write-Host “Changed is now:” $Changed”. After it was set OUTSIDE a function”
calculateValue;
Write-Host “Changed is now:” $Changed”. After it was set INSIDE a function as global”
$Changed = $False;
Write-Host “Changed is now:” $Changed”. After it was set OUTSIDE a function again”