Variables
Prerequisites: Your first commands
A variable stores a value — text, a number, or any object — so you can
use it later. Variable names start with $.
$city = 'Lagos'
$temperature = 24
"It is $temperature degrees in $city"
$temperature = 27
$temperature += 1
$temperature
It is 24 degrees in Lagos
28
- Assign with
=(spaces around it are fine). +=,-=,*=,/=update a variable in place;$count++adds one.- Variable names aren't case-sensitive:
$Cityand$cityare the same.
Variables can hold objects — and whole results
$numbers = 1..10
$evens = $numbers | Where-Object { $_ % 2 -eq 0 }
$evens.Count
$evens -join ', '
5
2, 4, 6, 8, 10
Storing a command's output in a variable lets you reuse it without running the command again.
Automatic variables
PowerShell sets some variables for you:
| Variable | Holds |
|---|---|
$_ / $PSItem |
the current pipeline object |
$true, $false, $null |
Boolean values and "nothing" |
$HOME |
your home folder |
$PWD |
the current folder |
$PSVersionTable |
version information |
$env:NAME |
an environment variable, such as $env:PATH |
Common mistakes
- Forgetting the
$:city = 'Lagos'tries to run a command calledcity. - Using a variable before assigning it — it's
$null, so things quietly go wrong.Set-StrictMode -Version Latest(Level 3) turns that into an error.
Practice
Store a product name and a price in variables and print
Coffee costs 3.5.
Show solution
$product = 'Coffee'
$price = 3.5
"$product costs $price"
Coffee costs 3.5