L4. Variables, Types, Arrays, and Hashtables
Build reliable scripts by understanding variables, type conversion, arrays, hashtables, PSCustomObject, string interpolation, and when to use each data structure.
Variables and Types
PowerShell variables start with $. They can hold strings, numbers, dates, arrays, hashtables, command output, or full objects.
$name = 'Protego'
$count = 3
$now = Get-Date
$services = Get-Service
$services.GetType().FullNamePowerShell is flexible, but production scripts should still be explicit where mistakes are expensive:
[int]$retryCount = 3
[datetime]$deadline = '2026-07-15'
Arrays
Arrays hold ordered lists:
$servers = @('web01', 'web02', 'db01')
$servers[0]
$servers | ForEach-Object { "Checking $_" }For very large collections, repeatedly using += can be inefficient. Prefer collecting pipeline output or using a generic list when performance matters.
Hashtables
Hashtables store key-value pairs:
$config = @{
Environment = 'Prod'
Region = 'EastUS'
RetentionDays = 30
}$config['Region']
$config.RetentionDays
Hashtables are also used for splatting, which makes long commands safer to read:
$params = @{
Path = '.\report.txt'
Value = 'Inventory complete'
Encoding = 'utf8'
}
Set-Content @params
PSCustomObject
[pscustomobject]@{
ComputerName = $env:COMPUTERNAME
PowerShell = $PSVersionTable.PSVersion.ToString()
Timestamp = (Get-Date).ToString('o')
}Use [pscustomobject] when you want clean structured output from your own script.
Lab
- Create an array of three hostnames.
- Create a hashtable with environment settings.
- Use splatting with
Get-ChildItem. - Build a
[pscustomobject]inventory record.
Sources
- Microsoft Learn: Everything you wanted to know about hashtables
- ✓Variables can hold full objects, not only strings
- ✓Arrays are ordered lists; hashtables are key-value maps
- ✓Splatting passes a hashtable of parameters to a command using @params
- ✓Use PSCustomObject for clean structured script output
- ✓Add explicit type annotations when conversion errors would be risky
1. Which syntax passes a hashtable of named parameters to a command?
2. When should you use PSCustomObject?
Recommended: Pluralsight
This free course covers the theory. Pluralsight adds structured video courses, hands-on Azure labs, and timed practice exams to make it stick before exam day.