EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 360+ Courses All in One Bundle
  • Login
Home Data Science Data Science Tutorials PowerShell Tutorial PowerShell Global variable
Secondary Sidebar
PowerShell Tutorial
  • Basics
    • PowerShell Restart Service
    • PowerShell comment
    • PowerShell Map Network Drive
    • PowerShell Append to File
    • PowerShell print
    • What is PowerShell
    • Uses Of Powershell
    • PowerShell Empire
    • PowerShell Parameter
    • PowerShell Stop Service
    • PowerShell Versions
    • How To Install PowerShell
    • PowerShell uninstall module
    • How to Use PowerShell?
    • PowerShell Logging
    • PowerShell Tools
    • PowerShell Commands
    • PowerShell Version Command
    • PowerShell Administrator
    • PowerShell Modules
    • PowerShell Registry
    • PowerShell block Comment
    • PowerShell Verbs
    • PowerShell list
    • PowerShell add user to group
    • PowerShell Write to Console
    • Variable in PowerShell
    • PowerShell New Line
    • PowerShell prompt for input
    • PowerShell File Extension
    • Powershell Remotesigned
    • PowerShell Write to File
    • PowerShell Ping
    • PowerShell wget
    • PowerShell Global variable
    • PowerShell Get-ADGroup
    • Array in PowerShell
    • PowerShell Multidimensional Array
    • PowerShell Array of Strings
    • PowerShell? join array
    • Useful PowerShell Scripts
    • String in PowerShell
    • PowerShell Switch Statement
    • PowerShell Function Parameters
    • PowerShell vs PowerShell ISE
    • PowerShell test-connection
    • PowerShell Test-NetConnection
    • PowerShell GUI
    • PowerShell Variable in String
    • PowerShell Active Directory
  • Variables
    • PowerShell Variables
    • PowerShell Environment Variables
    • PowerShell set environment variable
    • Hashtable in PowerShell
    • Set Variable in PowerShell
  • Operators
    • PowerShell Operators
    • Comparison Operators in PowerShell
    • Logical Operators in PowerShell
    • PowerShell Boolean
    • PowerShell Like Operator
  • cmdlet
    • PowerShell Wait
    • PowerShell Match
    • cmdlets in PowerShell
    • Start PowerShell from cmd
    • Add-Content in PowerShell
    • Get Help in PowerShell
    • PowerShell Copy-Item
    • PowerShell Remove-Item
    • PowerShell Move-Item
    • Get Command in PowerShell
    • PowerShell Run Command
    • Windows PowerShell ISE
    • Windows Powershell Commands
    • WinRM PowerShell
    • PowerShell Date
    • Powershell Write-Host
    • PowerShell Get-ChildItem
    • PowerShell Sort-Object
    • PowerShell Where Object
    • PowerShell Set-Content
    • PowerShell Set-Location
    • PowerShell Invoke-Command
    • PowerShell Invoke-Webrequest
    • PowerShell Get-Location
    • PowerShell Get-Date
    • PowerShell Get-Service
    • PowerShell Test-Path
    • Powershell Module Path
    • PowerShell Out-File
    • PowerShell if File Exists
    • Powershell Copy File
    • PowerShell Delete File
    • PowerShell New-Item
    • PowerShell Rename-Item
    • PowerShell ComputerName
    • PowerShell Get-Content
    • PowerShell Get-Item
    • PowerShell Get-ADUser
    • PowerShell Grep
    • PowerShell Concatenate String
    • PowerShell Get-Process
    • PowerShell Count
    • PowerShell pause
  • Control Statements
    • If Statement in PowerShell
    • If Else in PowerShell
    • Else If in PowerShell
    • Loops in PowerShell
    • For loop in PowerShell
    • PowerShell While Loop
    • PowerShell do while
    • PowerShell Loop through Array
    • PowerShell add to array
    • PowerShell ForEach Loop
    • PowerShell Break
    • PowerShell Continue
    • Switch Case in PowerShell
    • PowerShell If-Not
    • Try-catch in PowerShell
  • Functions
    • PowerShell Functions
    • PowerShell String Functions
    • powershell nslookup
    • PowerShell here string
    • PowerShell Wildcards
    • Regex in PowerShell
    • PowerShell not like
    • PowerShell Filter
    • PowerShell Sleep
    • PowerShell where
    • PowerShell join string
    • PowerShell Exit
    • PowerShell null
    • PowerShell Dictionary
    • PowerShell Location
    • PowerShell Start-Service
    • PowerShell is not digitally signed
    • PowerShell Uptime
    • PowerShell Create Directory
    • PowerShell Trim
    • PowerShell Join-Path
    • PowerShell Execution Policy
    • PowerShell SubString
    • PowerShell Format Table
    • PowerShell Import Module
    • PowerShell ForEach Object
    • PowerShell Alias
    • PowerShell Scheduled Task
    • PowerShell Convert String to Date
    • PowerShell Split String
    • PowerShell Multiline String
    • PowerShell MultiLine Comment
    • PowerShell Rename Folder
    • PowerShell Delete Folder
    • PowerShell String Replace
    • PowerShell join
    • PowerShell xcopy
    • PowerShell Base64
    • PowerShell Tail
    • PowerShell User List
    • PowerShell remove User from group
    • PowerShell JSON Format
    • PowerShell Send Mail
    • PowerShell Convert to String
    • PowerShell Start-Process
    • PowerShell change directory
    • PowerShell Open File
    • PowerShell Batch File
    • PowerShell ZIP
    • PowerShell unzip
    • PowerShell XML
    • PowerShell XML Parsing
    • Remote PowerShell
    • PowerShell Escape Character
    • PowerShell scriptblock
    • PowerShell Executable Location
    • PowerShell Import-CSV?
    • PowerShell Export CSV
  • Interview Questions
    • PowerShell Interview Questions

PowerShell Global variable

PowerShell Global variable

Introduction to PowerShell global variable

Variables are an integral part of PowerShell. There are many types of variables; this article will focus on global variables. Global variables are the ones which are available to all scripts, functions, or any cmdlet within the current session. Usually, global variables are declared at the beginning, mostly at the top. The major use of a global variable is its reusability. This article will explain in detail global variables, syntax its use, along with appropriate examples.

Syntax of PowerShell Global variable

The way of creating a global variable is as follows

Start Your Free Data Science Course

Hadoop, Data Science, Statistics & others

$global:test="This is a test"

or

$global:test = $null

Example:

Write-Host "Example of global variable in PS" -ForegroundColor Green
$global:test=""
Function test ($tes)
{
$global:test+=$tes
}
test -tes "this "
$global:test+="is "
$global:test+="test "
Write-Host $global:test -ForegroundColor Green

Output:

PowerShell Global variable output 1

Example:

Setting a global variable through a function

Write-Host "Demo of calling global variable from function" -ForegroundColor Green
$global:fln = $null
function getfn ($fn, $ln)
{
$fn +"  "+ $ln
}
$global:fln = getfn vignesh krishnakumar
Write-Host "the function value is set to global variable" -ForegroundColor Green
write-Host "the value is "$global:fln
$global:fln1 = $null
function getfn1 ($fn1, $ln1, $chn1)
{
$fn1 +"  "+ $ln1 +"  "+ $chn1
}
Write-Host "Demo of global variable with function as three parameters" -ForegroundColor Green
$global:fln1 = getfn1 vignesh krishnakumar Chennai
Write-Host " the value is " $global:fln1

Output:

PowerShell Global variable output 2

Example:

Input:

Write-Host "Demo of passing global variable as a parameter to a function"
Write-Host "global variable needs to be declared as reference"
$global:finalsum =""
function sum ($no1, $no2, [REF]$resr)
{
$resr.Value = $no1 + $no2
}
#You can then call it like this:
sum 51 61 ([REF]$global:finalsum)
Write-Host " the value of the global variable is" $global:finalsum
$global:finalsum1 =""
function sum1 ($no11, $no22, $no33,$no44,[REF]$resr1)
{
$resr1.Value = $no11 + $no22 +$no33 + $no44
}
#You can then call it like this:
sum1 51 61 71 81 ([REF]$global:finalsum1)
Write-Host " the value of the global variable is" $global:finalsum1

PowerShell Global variable output 3

Advantages of Global Variable

  • It can store all types of data types values such as strings, objects, arrays, integers, and hast tables.
  • It can store a collection of different object types
  • Every variable is allotted a memory
  • If a value is not assigned to a global variable, it is considered empty by default.
  • Though it is not mandatory, it is always best to declare the global variables at the top for easy understanding.

Scope Hierarchy

As specified prior, once you dispatch a PowerShell session, PowerShell creates some things for you within the worldwide scope. These things can be capacities, factors assumed names, or PSDrives. Anything you define in your PowerShell session will be defined within the global scope also. Since you’re within the worldwide scope by default, if you are doing something that makes another scope like executing a script or running a workshop, a child scope will be made with the parent being the worldwide scope. Scopes are like forms with parents and children. So anything that’s characterized in a parent scope, the worldwide scope, in this case, will be available within the child’s scope. But these things are as they were editable within the scope they were characterized in.

Different types of scope modifiers:

Global: this denotes the global scope

Local: This denotes the only the current scope

Private: this denotes that the item is private and available within the current scope

Script: this denotes that the item can be accessed throughout the script

Using: This is used to access items from other scripts

Workflow: this denotes items used within a workflow

Using Modifier:

This is used to work with items in a remote cmdlet. Whenever anything that needs to be accessed outside the current session, the using modifier should be used. This is one step higher than the global variable. Some example cmdlets are Start-Job and Invoke-Command.

Example:

Input:

Write-Host "Demo of setting global variable value" -ForegroundColor Green
Set-Variable -Name "TD" -Value (Get-Date) -Scope global
Get-Variable -Name "TD"
Set-Variable -Name "NAME1" -Value "vignesh" -Scope global
Set-Variable -Name "age1" -Value "28" -Scope global
Set-Variable -Name "city" -Value "chennai" -Option Private -Scope global
Set-Variable -Name "status" -Value "married" -Scope global
Set-Variable -Name "gender" -Value "male" -Scope global
Get-Variable -Name "NAME1"
Get-Variable -Name "age1"
Get-Variable -Name "city"
Get-Variable -Name "status"
Get-Variable -Name "gender"

Output:

output 4

Example:

Input:

Write-Host "Example of global variable in PS" -ForegroundColor Green
$global:eg=""
Function test ($par)
{
$global:eg+=$par
}
test -par "welcome"
$global:eg += "user "
$global:eg+="mark "
Write-Host $global:eg -ForegroundColor Green
$global:abc = $null
function geabcdtfn ($fn, $ln)
{
$fn +"  "+ $ln
}
$global:abc = geabcdtfn vijaya sethupathi
write-Host "the value is "$global:abc
$global:fln1 = $null
function getfn1 ($fn1, $ln1, $chn1)
{
$fn1 +"  "+ $ln1 +"  "+ $chn1
}
Write-Host "Demo of global variable with function as three parameters" -ForegroundColor Green
$global:fln1 = getfn1 vignesh krishnakumar Chennai
Write-Host " the value is " $global:fln1
Set-Variable -Name "tdate" -Value (Get-Date) -Scope global
Set-Variable -Name "mark1" -Value "100" -Scope global
Set-Variable -Name "mark2" -Value "90" -Scope global
Set-Variable -Name "mark3" -Value "100" -Option Private -Scope global
Set-Variable -Name "mark4" -Value "100" -Scope global
Set-Variable -Name "total" -Value "390" -Scope global
Get-Variable -Name "mark1"
Get-Variable -Name "mark1"
Get-Variable -Name "mark1"
Get-Variable -Name "mark1"
Get-Variable -Name "total"
Get-Variable -Name "tdate"

Output:

output 5

output 6

Conclusion

Thus, the article explained in detail the global variable in PowerShell. It explained in detail how to define a global variable, set a value to the global variable, pass the global variable to a function, and set the value returned by a function to a global variable. Though global variables are available for the entire session, it is not advisable to create all the variables as global variables, leading to bad practice. To learn more in detail, it is advisable to write sample scripts and practice them.

Recommended Articles

This is a guide to the PowerShell Global variable. Here we discuss how to define a global variable and how to set a value to the variable. You may also have a look at the following articles to learn more –

  1. PowerShell Location
  2. PowerShell New Line
  3. PowerShell Dictionary
  4. PowerShell Exit
Popular Course in this category
PowerShell Training (2 Courses, 1 Project)
  2 Online Courses |  1 Hands-on Project |   4+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Shell Scripting Training (4 Courses, 1 Project)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
Data Visualization Training (15 Courses, 5+ Projects)4.7
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Database Management
  • Machine Learning
  • All Tutorials
Certification Courses
  • All Courses
  • Data Science Course - All in One Bundle
  • Machine Learning Course
  • Hadoop Certification Training
  • Cloud Computing Training Course
  • R Programming Course
  • AWS Training Course
  • SAS Training Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2023 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Data Science Course

Hadoop, Data Science, Statistics & others

By continuing above step, you agree to our Terms of Use and Privacy Policy.
*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more