Variables - An Unchanging Constant

Variables are used to store information temporarily while a program is running. As implied by their name they are generally changeable but not in every case. In many languages variables are statically typed, which means that when you first declare a variable you define what type of variable it is. The following example shows how variables are declared in C++, which is statically typed.

//Ints are integers, or whole numbers.
int aNumber = 6;

//Doubles are numbers with decimals
double aDouble = 6.45;

//Strings hold a series of alphanumeric characters
string aString = "Qurtyslyn";

//Bools are Boolean values, either True or False
bool aBoolean = true;
A block of code demonstrating how variables are declared in C++ which is statically typed.

Some languages (such as Powershell and Javascript) are dynamically typed which means that it is not necessary to set a type when declaring a new variable. The variable's type is determined by what it contains.

#Declaring a variable containing an integer
$aNumber = 5

#Declaring a variable containing a decimal is the same process
$aDouble = 5.67

#Declaring a variable containing a string
$aString = "Qurtyslyn"

#Declaring a variable containing a boolean
$aBoolean = $true
A block of code demonstrating how variables are declared in Powershell which is dynamically typed.

While the syntax (syntax is just the rules that define how a particular language is structured) of the code is a little different, the basic format is the same. In C++ you can see that the variable's type is declared when the variable is declared, while in Powershell no type is declared. In C++, you can only set a variable's value to whatever it has been declared as, while in Powershell you can change from an int to a string on the fly if you want to, although I'd recommend against it as it can get confusing.

Even though Powershell does not require you to set a variable's type when you declare it, you can constrain it to a specific type. This isn't generally necessary, but can sometimes be helpful.

#Constraining a variable to an int when declaring it
[int]$aNumber = 5

#Constraining a variable to a string when declaring it
[string]$aString = "Qurtyslyn"
A block of code demonstrating how to constrain a variable to a specific type.

Variables in Powershell

Powershell defines seven different kinds of variables that can be used in your code: static variables, ordinary variables, instance variables, array elements, hashtable key/value pairs, parameters, and variables on provider drives. We'll dive into each below.

Static Variables

Static variables are not unchangeable, but rather there is one instance of the variable that is available in the global scope. Scope refers to the part of the program where a resource is available. This will come more into play with loops and functions. Being in the global scope means that a variable is available in any piece of code.

#An example of a static variable that is predefined in Powershell
$circumference = 2 * [Math]::PI * $radius
Using the [Math]::PI static variable to calculate the circumference of a circle.

In this case, the variable PI has been declared in the Math module of Powershell.  Rather than trying to define PI in every script that needs it, you can call the static variable for it.

Ordinary Variables

Ordinary variables are just that, ordinary. They're the variables you'll use most often in Powershell. An ordinary variable is defined by an assignment expression or by a for-each statement, which is beyond the scope of this article. Assignment expressions are any expression that contains a single = operator. Assignment expressions can be broken into two groups, simple assignments and compound assignments.

Simple assignments are where the value of the variable on the left hand side of the = is replaced by the value on the right hand side.

#Setting a variable to a static value
$Variable = "a static value"

#Setting a variable to the value of another variables
$Variable = $AnotherVariable

#Setting a variable to the result of an equation
$Variable = 5 + 6 * (4-2)
A demonstration of simple assignments in Powershell.

In a compound assignment the variable on the left of the = is being used as part of an equation before being set to the result of that equation. You can identify these assignments as in addition to the = they will have an additional operator to the left of the = indicating what they do.

#A compound assignment, take variable $A and add 7 to it.
$A += 7

#Simple assignment equivilent
$A = $A + 7

#A compound assignment, take variable $A and multiply it by 20.
$A *= 20

#Simple assignment equivilent
$A = $A * 20
Equations demonstrating a compound assignment and a simple assignment that have the same result.

Compound assignments can be used with any of the mathematical operators, +, -, *, /, and %. While the end result is the same, compound assignments have the advantage that the target variable is only evaluated once, making it slightly less resource intensive while sacrificing some readability for newer programmers.

Instance Variables

An instance variable is a data member of an object, that belongs to that particular object's type, rather than the variable itself. For instance, the length instance variable exists as a defined part of a string variable.

#Defining a variable with a string, and out putting that string's length
$String = "A bunch of fools play with matches."
$String.Length

#$String.Length will equal 35, as $String is 35 characters long.
Demonstrating an instance variable with $String.Length

The length instance variable exists only on certain variable types, calling length on an integer will not return the length of the integer, but rather just 1.

Array Elements

In simple terms, an array is an indexed collection of variables all gathered into one list. The elements of this array can be accessed with the [] operator. There are multiple ways to declare an array, which will be discussed in another article. Note that in most programming languages, indexes begin at 0 (zero).

#Declaring an array
$Array = @("A","List","Of","Things")

#Accessing an Array Element
$Array[0]

#$Array[0] will output "A" as that is the first item in the Array

#Accessing an Array Element using the range operator (..)
$Array[0..2]

#$Array[0..2] will output "A", "List, and "Of"

#Accessing the last element of an Array
$Array[-1]

#$Array[-1] will output "Things"
Demonstrating accessing an element of an array

Hashtable key/value pairs

Hashtables are similar to arrays in that they're an indexed collection of variables all gathered into one list. Instead of being indexed by number like an array they are instead indexed by key; a key can be of any variable type and is not restricted to being a whole number. This makes them more useful for storing defined information, such as a person's information. Accessing the variable is done using the same [] operator as an array, but instead of the index number, the name of the key is used.

#Declaring a Hashtable
$NewPerson = @{FirstName = "Qurtys"; LastName = "Lyn"; EmployeeID = 8675309}

#Accessing a hashtable by key
$NewPerson[FirstName]

#$NewPerson[FirstName] will output "Qurtys"
Demonstrating declaring a hashtable and accessing it's key/values

The name of the key does not have to be a string, any type can be used, including ints and booleans.

Parameters

Parameters are temporary storage variables created as a result of a 'parent' command (typically a function or a script) being called. At the time of the call, the parent can be passed additional information that is then stored in the parameters. As soon as the parent command terminates, the parameter ceases to exist.

#Creating a Function with a parameter
function Return-Parameter
{
	#Parameters are set for the function using the param() function
    param($aParameter)
    
    return $aParameter
}

#Calling the function using a Parameter
Return-Parameter -aParameter "This string will be returned."
Demonstrating the creation and call of a function with a parameter

Variables on Provider Drives

A provider allows access to data that would otherwise not be easily accessible. There are several in Powershell, including Environment Variables and the FileSystem. These are variables that access data of the system Powershell is being run on, rather than contained in Powershell itself.

#Getting the current User on the computer using an environment variable
$Env:USERNAME

#Getting the location of the current users User Folder
$Env:USERPROFILE

Variable Types

Mentioned above you can constrain a variable's value to a specific type in Powershell like some other languages require. I've listed some of the basic ones below.

Boolean

The Boolean type is declared with bool. There are only two values of this particular type, True and False, which are represented by the variables $True and $False respectively.

Character

The Character type is declared with char. It can contain any single Unicode character.

Integer

The Integer type is declared with int. It can contain any whole number from -2147483648 to +2147483647.

In addition to int, you can declare using the names long or byte, which have ranges of -9223372036854775808 to +9223372036854775807, and 0 to +255 respectively.

Decimals

There are three type declarations for decimal numbers, float, double, and decimal. Floats are between -2,147,483,648 and + 2,147,483,647 (same as an int) but can only contain 7 total digits (not counting the decimal point), and doubles are between 5.0 × 10−345 to 1.7 × 10308 and can contain 15-16 digits (depending on size). Decimal can between -79228162514264337593543950335 to 79228162514264337593543950335

Strings

Strings are declared with string. They contain zero or more characters in series.