Categories Tutorials

Conquer the world with PowerShell global variable

Variables are the building blocks of every program. They are nothing but objects that allow us to store specific values in them for later processing or for displaying its value to the user. For example, you can store your age in a variable and use it for further processing, such as $MyAge=25. You can do a lot of processing with this variable and can use it instead of hardcoding the value at all places. This way, when you want to change the value of your age, you can simply go and change the value of the variable instead of making multiple changes throughout the program. PowerShell is all about making things easier, and there are many types of variables in PowerShell that do this. One such type is the PowerShell global variable, which is what we will be focusing on in this article.

What is a global variable?

Every variable has a certain scope. When you define a variable inside a function, it can be accessed only within that function and not outside. For example, if you say,

function calculateAge
{
$MyAge =35;
Write-Host $MyAge;
}

When you run this method, you’ll get the output:

function calculateAge
{
$MyAge =35
}
Write-Host $MyAge

When you run the above script, the value will be null because that’s the default value of any variable in PowerShell.

Likewise, there are many scopes, depending on where it is defined and this limits the access of these variables across different parts of the program. But if you want to access a variable throughout your program and across different methods, you should use a global variable as it is accessible to scripts, functions, and cmdlets across the entire session.

Things to know about a PowerShell global variable

Now that you have an idea, let’s expand the global variables a bit further and see some of its features.

  • Stores all types of values such as integers, strings, arrays, hash tables, and objects.
  • It can contain a collection of different objects.
  • A certain amount of memory is allocated to every variable.
  • Every global variable has to be preceded by the "$" symbol.
  • It is a good programming practice to declare a global variable right at the beginning of a program.
  • If you don’t assign a value to your variable, it will be null by default.
  • The name of the global variable can contain a combination of alphabets, numbers, and an underscore (_). If you want to use other special characters, enclose the full name of the variable with braces.

Declaring a PowerShell global variable

To declare a PowerShell global variable, simply use the below syntax.

$global: myVariable ="This is my first global variable."

If you choose not to give any value to it, you can explicitly assign a null value to it.

$global: myVariable =$null

It is important to note that you have to mention the word “global” to let PowerShell know that this variable should be made available throughout the program.

This can bring up an important question. What happens if a global variable and a local variable share the same name? Well, the local variable will take precedence over the global one within its scope. If you access it outside the scope of the local variable, the global value will be used. For example:

$global:myAge =25;
function calculateAge
{
$MyAge =35;
Write-Host $MyAge "inside the function";
}
Write-Host $MyAge "outside the function";
calculateAge;

The output will be:

35 inside the function
25 outside the function

Clearly, the value of the local variable took precedence inside the function, but outside the function, the local variable had no meaning, so the global one was used.

Setting the value of a PowerShell global variable

In general, there is a lot of confusion about where and how you can set the value for a PowerShell global variable, and in this section, we’ll clear some of these confusions.

Setting the value of a PowerShell global variable in a function

You can set the value of a global variable from a function. Let’s see an example.

$global:finalvalue - $null;
function calculateValue ($str1, $str2)
{
$str1 + $str2;
}
$global:finalvalue = calculateValue ("Hello", "world");
Write-Host "The final value is:" $global:finalvalue;

The output of this program is The final value is: Hello world. If you notice, the global variable’s value was set inside the function.

Passing the PowerShell global variable as a parameter to the function

You can also pass a global variable as a parameter to a function and set its value inside the function. But of course, you’ll have to pass the global variable as a REF object.

$global:finalvalue = $null;
function calculateValue ($num1, $num2, [REF]$answer)
{
$answer.Value = $num1 + $num2;
}
calculateValue 2 3 ([REF]$global:finalvalue);
Write-Host "The final value is:" $global:finalvalue;

The difference here, when compared to the previous example, is that you’re setting the value of the global variable inside a function by passing this also as a parameter to the function.

Using Set-Variable cmdlets

The easiest way to set the values to a PowerShell global variable is to use the Set-Variable cmdlets:

Set-Variable -Name "finalValue" - value "5" -scope global
Get-Variable -Name "finalValue"

This will display the value of 5. Note that you have to mention the scope of the variable as global.

Creating read-only PowerShell global variable

The Set-Variable cmdlet comes with an optional parameter that can be used to determine the nature of the global variable. For example:

Set-Variable -Name "finalValue" - value "5" -scope global -option Read-Only

The above code will create a global variable and will set a value to it, but it will be a read-only global variable. Likewise, to make its value a constant, the code will be:

Set-Variable -Name "finalValue" - value "5" -scope global -option constant

A word of caution

Now that you know all about global variables, a word of caution before you start using it in your program. A PowerShell global variable is not the most preferred way to create variables or store values because they have no access control. In other words, it is hard to keep track of the value of a global variable as it can be changed anywhere in a program. Also, testing them is very difficult as they are tightly coupled with the code,

These are some reasons why experienced programmers don’t use global variables often as they can lead to some nasty and hard-to-find bugs in big programs.

Understand the implications

Thus, a PowerShell global variable is one that is available throughout the program and can be accessed anywhere. You can set its value in many ways and can create it with many characteristics such as a private global variable, read-only, constant, and more.

But exercise caution while using a PowerShell global variable and make sure you understand its importance and implications in your code.

Featured image: Pixabay

Lavanya Rathnam

Lavanya Rathnam is a professional writer of tech and financial blogs. Creative thinker, out of the boxer, content builder and tenacious researcher who specializes in explaining complex ideas to different audiences.

Share
Published by
Lavanya Rathnam

Recent Posts

Simplifying cloud complexity: 4 roads to the same destination

As cloud computing grows, the sheer number of options can be a problem. But there…

36 mins ago

Building Exchange 2019 from scratch: Setting up a domain controller

If you are building a new Exchange 2019 environment from scratch, you will have to…

4 hours ago

RAID 1 vs. RAID 5: When to use each level and why

Redundant array of independent disks (RAID) is the logical grouping of two or more disks…

23 hours ago

Microsoft 365 adds online scheduling to Microsoft Bookings app

Microsoft 365 users have access to an app called Microsoft Bookings. Before you dismiss it…

1 day ago

Biometrics authentication: Where the technology is now — and where it’s going

As cyberthreats rise in number and complexity, biometrics authentication technology has seen rapid adoption and…

4 days ago

Remote work vulnerabilities: Tips on avoiding a nightmare scenario

Remote work is likely to remain permanent — and so will the vulnerabilities it brings…

4 days ago