L4. Variables, Types, Arrays, and Hashtables
Course outlineLesson 4 of 10
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-Process)
$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 $_" }Before PowerShell 7.5, repeatedly appending to an array with += reallocates it and can be expensive. PowerShell 7.5 optimized array addition. Collecting pipeline output with @(...) or using a generic list remains useful when supporting older versions. Array subexpressions also keep zero or one result as an array.
Hashtables
Hashtables store key-value pairs:
$config = @{
Environment = 'Prod'
Region = 'EastUS'
RetentionDays = 30
}
$config['Region']
$config.RetentionDaysHashtables 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 = [System.Environment]::MachineName
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: create$listParams = @{ Path = "."; File = $true }, then runGet-ChildItem @listParams. - Build a
[pscustomobject]inventory record.
References
- Microsoft Learn: Everything you wanted to know about hashtables
- PowerShell array behavior
- PowerShell array performance
- Portable machine name
Continue Learning
- ✓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?