Variables
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.14PS > $pi3.14
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().NameString
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 = 25PS > $age25PS > [Int]$age = "twenty five" # Results in an errorCannot 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
- Anonymous contributorAnonymous contributor
- Anonymous contributor
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.