TExcelTAD
Home › PowerShell › PowerShell Variables

PowerShell Variables

A variable stores a value so you can use it later. In PowerShell every variable name starts with a dollar sign $. You don't declare variables in advance: assigning a value creates the variable.

powershell · try it yourself
$name = 'Ada'
$year = 1843
$languages = 'PowerShell', 'Python', 'Rust'

$name
$year
$languages
Ada
1843
PowerShell
Python
Rust

Assigning a comma-separated list creates an array, which prints one element per line.

Naming rules

  • Names are case-insensitive: $Total, $total and $TOTAL are the same variable.
  • Use letters, digits and underscores. Descriptive camelCase or PascalCase names ($logFolder, $MaxRetries) are the convention.
  • Names with spaces or special characters need braces: ${file name}. Avoid them.
  • Don't overwrite automatic variables such as $_, $true, $false, $null, $PWD, $HOME, $Error, $args or $input.

Variables inside strings

Double-quoted strings expand variables; single-quoted strings keep the text exactly as written:

powershell · try it yourself
$item = 'coffee'
$price = 3.2
"One $item costs $price euros"
'One $item costs $price euros'
"Two cost $($price * 2) euros"
"The item has $($item.Length) letters"
One coffee costs 3.2 euros
One $item costs $price euros
Two cost 6.4 euros
The item has 6 letters

Only the simple $name is expanded inside a string. For an expression or a property, wrap it in the subexpression operator $( … ). Writing "$item.Length" would print coffee.Length.

Multiple assignment and swapping

powershell · try it yourself
$x, $y = 10, 20
"x=$x y=$y"
$x, $y = $y, $x          # swap without a temporary variable
"x=$x y=$y"

$first, $rest = 'a', 'b', 'c', 'd'
$first
$rest -join ','

$a = $b = 0              # chain assignment
"a=$a b=$b"
x=10 y=20
x=20 y=10
a
b,c,d
a=0 b=0

When there are more values than variables, the last variable receives all the remaining values as an array.

Null and unset variables

A variable that was never assigned is $null. That is not an error, which can hide typos. Turn on strict mode to make PowerShell complain instead:

powershell · try it yourself
"Before: [$undefinedVariable]"
$null -eq $undefinedVariable

Set-StrictMode -Version Latest
try {
    "After: [$undefinedVariable]"
} catch {
    "Error: $($_.Exception.Message)"
}
Before: []
True
Error: The variable '$undefinedVariable' cannot be retrieved because it has not been set.

Tip: Put Set-StrictMode -Version Latest at the top of your scripts. It catches misspelled variable names, reading properties that don't exist and other silent bugs.

Variable cmdlets

Variables live on the Variable: drive, and a few cmdlets manage them directly. They're useful when a variable's name is itself stored in a string:

powershell · try it yourself
New-Variable -Name maxUsers -Value 50 -Option ReadOnly
$maxUsers
try { $maxUsers = 60 } catch { "Cannot change: $($_.Exception.Message)" }

Set-Variable -Name color -Value 'teal'
Get-Variable -Name color -ValueOnly
Remove-Variable -Name color
Test-Path Variable:color
50
Cannot change: Cannot overwrite variable maxUsers because it is read-only or constant.
teal
False

-Option ReadOnly makes a variable that can't be reassigned (removal needs -Force); -Option Constant can never be changed or removed.

Test yourself

What does 'Total: $sum' (single quotes) print when $sum = 5?

  1. Total: 5
  2. Total: $sum
  3. Total:
  4. An error

Which string prints the length of $name correctly?

  1. "$name.Length"
  2. "$($name.Length)"
  3. "${name.Length}"
  4. '$($name.Length)'

What does Set-StrictMode -Version Latest change?

  1. Variables must have a type
  2. Using an unassigned variable becomes an error
  3. Strings become case-sensitive
  4. Scripts must be signed