Product and service reviews are conducted independently by our editorial team, but we sometimes make money when you click on links. Learn more.

PowerShell Basics: Using Variables, Arrays and Hashtables

PowerShell Basics: Using Variables, Arrays and Hashtables

In this PowerShell tutorial we take a closer look at variables, arrays and hashtables, which allow you to store, retrieve and manipulate information with PowerShell.

Windows PowerShell is all about making IT Pros more efficient in their daily tasks. PowerShell is intuitive enough that entry-level or mid-tier admins can begin to learn the language, use cmdlets from the console, and even begin to write reasonably simple scripts.

Once your PowerShell scripts begin to become more complex, you'll need to start working with aspects of PowerShell that will take you back to the programming classes you took in college. Variables in particular are essential for scripting, because they enable you to pass information between parts of your script.

Assigning and Referencing PowerShell Variables

You're probably familiar with the concept of variables on some level, whether it's from prior experience in programming or from mathematics. Values can be assigned to a variable in order to reference that variable throughout your PowerShell script. The use of variables allow you to ensure the value stays consistent throughout the script, makes it easier to change the value later (either manually or programmatically), and generally makes your script much more readable.

Variable names in PowerShell begin with a $, as in $UserName, and values are assigned using =, like $UserName = "John Smith" or $UserAge = 42. PowerShell supports a huge number of variable types; such as text strings, integers, decimals, arrays, and even advanced types like version numbers or IP addresses.

y default, PowerShell will attempt to guess the variable type to be used, but this can be enforced by indicating the type prior to the variable name as in [int32]$UserAge=40. In cases where the assigned value does not match the enforced type, the value will be converted if possible, or an error will be produced.

Occasionally the need arises to dynamically assign or modify a variable's value rather than simply assigning a static value. This could involve performing a mathematical operation on a number or adding text to a string. Numerical values can be assigned or modified using standard math operators like +, -, *, and / as in the following examples:

$secondsPerDay = 24 * 60 * 60
$weeksPerYear = 365 / 7

Numerical values can also be incremented or decremented using ++ or – without having to add or subtract 1 from the value. These two examples have the same effect, increasing the value of the variable by 1:

$myNumber = $myNumber + 1

PowerShell uses the addition operator (+) to concatenate, or link text strings together. Later versions of PowerShell also support simply inserting a variable into a double-quoted string (as opposed to single quotes), though this technique should be used carefully in order to maximize backwards compatibility.

$website = ""
$myString = "My favorite website is" + $website
$myString = "My favorite website is $website"

Variables can also be used to retain information returned from cmdlets. This is particularly handy if your script calls for the same set of information to be used multiple times. Rather than running the same cmdlet multiple times you can assign it to a variable and use it later in the script as often as you'd like.

PowerShell Arrays and Hashtables

Arrays are most often used to contain a list of values, such as a list of usernames or cities. PowerShell offers several forms of arrays, each of which can be assigned and accessed in distinct ways. For the purposes of this article we're going to focus on the two most commonly used. Basic PowerShell arrays can be defined by wrapping a list of items in parentheses and prefacing with the @ symbol as in $nameArray = @("John","Joe","Mary"). Items within an array can be accessed using their numerical index, beginning with 0, within square brackets like so: $nameArray[0].

A more advanced form of array, known as a hashtable, is assigned with squiggly brackets prefaced by the @ sign. While arrays are typically (but not always) used to contain similar data, hashtables are better suited for related (rather than similar) data. Individual items within a hashtable are named rather than assigned a numerical index as in $user=@{FirstName="John"; LastName="Smith"; MiddleInitial="J"; Age=40}. Items within a hashtable are easily accessed using the variable and the key name as in $user.LastName.

Default Variables

One last thing of note about variables in PowerShell is that there are a host of default variables which automatically have values assigned. There are several variables beginning with the prefix "$env:" which can be leveraged to get things like the path to the Windows directory, temp folder, current user name or domain, and many other types of system information. A full list of the $env variables can be acquired using the following command:

Get-ChildItem env:

Several other additional variables are available such as $Home and $PsHome, which provide you the paths to the user's home directory and the PowerShell home directory respectively. The $Host variable returns an object containing information about the current PowerShell environment, whether it be the PowerShell ISE or the console. Finally, the $PSVersionTable contains information about the version of PowerShell installed, including $PSVersionTable.PSVersion.Major which shows the major PowerShell version available on the host running the script.

The PowerShell values for the Boolean values of True and False are automatically assigned to the $true and $false default variables.


More PowerShell How-Tos