Variables and Types
Scope: $variables, the core types, arrays, and hashtables.
All examples were run with PowerShell 7.5.
Variables start with $
$name = "Ada"
$age = 36
Write-Host "Hello, $name"
Assignment with =, expansion with $. Inside double-quoted
strings, variables expand:
$next = $age + 1
Write-Host "$name will be $next next year"
Single quotes are literal: 'Hello, $name' prints Hello, $name.
The types you'll actually use
| Type | Example | Notes |
|---|---|---|
[string] |
$s = "hello" |
Text |
[int] |
$n = 42 |
Whole numbers |
[double] |
$p = 3.14 |
Decimals |
[bool] |
$b = $true |
$true / $false (with the $!) |
[datetime] |
$d = Get-Date |
Dates are real objects |
$null |
$x = $null |
"Nothing here" |
PowerShell is dynamically typed — you rarely declare types, but
you can: [int]$n = "42" converts the string to 42. Explicit
casts are handy for input validation.
Arrays
$nums = 1, 2, 3
$nums = @(1, 2, 3) # same thing, explicit
$nums[0] # 1 — zero-indexed
$nums += 4 # append (builds a new array — fine for small ones)
$nums.Count # 4
$nums = 1, 2, 3 — commas make arrays. Note += copies the
array each time; for thousands of appends, use a
[System.Collections.Generic.List[int]] instead.
Hashtables: key-value lookup
$ages = @{
Ada = 36
Bob = 41
}
$ages["Ada"] # 36
$ages.Ada # 36 — dot works too
@{ } with = between keys and values. Missing keys return
$null (no error) — check with $ages.ContainsKey("Zed").
Ordered hashtables preserve insertion order:
$ordered = [ordered]@{
first = 1
second = 2
}
Automatic variables
PowerShell reserves some $ names:
| Variable | Meaning |
|---|---|
$_ / $PSItem |
Current pipeline object |
$? |
$true if the last command succeeded |
$HOME |
Your home directory |
$PWD |
Current directory (as an object) |
$Error |
List of recent errors |
$null |
Nothing (assignable, comparable) |
Don't name your variables these.
Type operators
"42" -is [int] # False — it's a string
42 -is [int] # True
"42" -as [int] # 42 — converts, or $null if it can't
-is tests, -as converts. Gentle and useful.
Check
- [ ] You use
$consistently and can explain single vs double quotes - [ ] You can build arrays and hashtables and index into them
- [ ] You know what
$_means
Next: Control Flow.