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.
$name = 'Ada'
$year = 1843
$languages = 'PowerShell', 'Python', 'Rust'
$name
$year
$languagesAda
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,$totaland$TOTALare 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,$argsor$input.
Variables inside strings
Double-quoted strings expand variables; single-quoted strings keep the text exactly as written:
$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
$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:
"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 Latestat 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:
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:color50
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?
- Total: 5
- Total: $sum
- Total:
- An error
Which string prints the length of $name correctly?
"$name.Length""$($name.Length)""${name.Length}"'$($name.Length)'
What does Set-StrictMode -Version Latest change?
- Variables must have a type
- Using an unassigned variable becomes an error
- Strings become case-sensitive
- Scripts must be signed