Anonymous contributor
Anonymous contributor
Published May 16, 2023
Contribute to Docs

A variable is a location in computer memory used to store data, usually to be referred to and manipulated in a program. Variables in PowerShell can store the results of commands and expressions.

Using a Variable

Variables in PowerShell are referenced using a dollar sign $ followed by a valid variable name.

PS > $pi = 3.14
PS > $pi

Creating a Variable

To create a variable, a variable reference is followed by an equal sign = and the value to be assigned.

$my_string_variable = "Hello, World!"

Variables names are not case-sensitive and can include spaces and special characters. The convention is to use only alphanumeric characters and the underscore _ character.

Variable Types

PowerShell dynamically assigns a type to a variable depending on the value assigned to it. .GetType().Name can be appended to a variable reference to get that variable’s data type.

PS > $my_string_variable.GetType().Name

Constrained Variables

A constrained variable is when a certain type can be enforced onto a variable via casting. To create a constrained variable, specify the type in brackets before the variable reference.

PS > [Int]$age = 25
PS > $age
PS > [Int]$age = "twenty five" # Results in an error
Cannot convert value "age" to type "System.Int32". Error: "Input string was not in a correct format."

Creating Multiple Variables

Multiple variables can be created with one statement using either the same value for all variables or multiple values.

$i = $j = $k = 0 # Same value
$number, $color, $bool = 25, "red", $false # Multiple values

All contributors

Looking to contribute?

Learn PowerShell on Codecademy