Working with PowerShell Global Variables

Hello,

I have been recently working on a number of PowerShell scripts which have several different “Functions” and found that I need to use variables that may have been previous set in a previous Function action. If a variable has been set in a function we are not able to just use the $Variable name in the following function so, as we don’t want to be prompting for the same information over and over again we can get around this issue by using Global Variables.

Example script without a global variable.

The following script shows that $accountname prompt has been specified in both functions increase the manual input require to action this script. This is an acceptable method if you wanted to be prompted but in a scripting scenario PowerShell can do a lot more to reduce the need for manual input.


Function Get-Mailbox {
$accountname = Read-Host -Prompt 'Please enter - Account Name'
Get-Mailbox -Name $AccountName
}

Function Set-Mailbox{
$accountname = Read-Host -Prompt 'Please enter - Account Name'
$password = Read-Host -Prompt 'Please enter - Password'
Set-Mailbox -Name $accountname -Password $password
}

Example script a global variable.

The following script is now using $Global:AccounName which sits outside of the Function blocks and looks at the $accountname variable when it has been specified or called into action. So any other functions within the script which require the $accountname variable will now be defined as $Global:AccountName as shown below.


$Global:AccountName = $accountname

Function Get-Mailbox {
$accountname = Read-Host -Prompt 'Please enter - Account Name'
Get-Mailbox -Name $AccountName
}

Function Set-Mailbox {
$password = Read-Host -Prompt 'Please enter - Password'
Set-Mailbox -Name $Global:AccountName -Password $password
}

This concludes how to use a Global Variable within your PowerShell script.

Remember: PowerShell is one of the most powerful tools available to all IT Professional and the best of it…. It’s FREE. It only requires you to launch the PowerShell Consoles whether that maybe PowerShell or PowerShell ISE. Start your PowerShell journey today and script actions you complete on a day to day basis to reduce the time and effort required.

Regards

The Author – Blogabout.Cloud

Leave a Reply

Your email address will not be published. Required fields are marked *