Arrays, Hashtables, and Custom Objects
Arrays, generic lists, hashtables and [PSCustomObject] in PowerShell: indexing, the += performance trap, iteration, CSV and JSON export, and Compare-Object.
By The Dark DebuggerUpdated 26 min read
Almost every useful script holds more than one value: a list of servers, a map of service names to ports, a table of results to export. This article covers the three structures you will use for that in PowerShell (arrays, hashtables and custom objects), plus generic lists for when arrays are too slow, and the cmdlets that turn collections into CSV, JSON and diffs. It assumes you know variables and types, the pipeline and the comparison operators.
Why the choice of structure matters
Picture a monthly access review. You export who has which role in production, compare it
with last month's export, and send the security team a list of what changed. Done with
plain strings and +=, the script is slow, the diff misses changes, and the CSV you attach
contains columns called IsReadOnly and SyncRoot. Done with the right structures, it is
twenty lines. Every one of those failures is shown below, and the
Where you'll use this section builds the working version.
Arrays
An array is an ordered list. The comma operator creates one, and @( ) guarantees one even
when there are zero or one items inside:
$servers = @('web01', 'web02', 'db01')
$ports = 80, 443, 8080
$empty = @()
$one = @('web01')
$servers.Count, $ports.Count, $empty.Count, $one.Count -join ' '
$servers.GetType().FullName3 3 0 1
System.Object[]A single-element array can also be written with a leading comma: ,'web01' has a Count
of 1. Arrays are Object[] by default, so one array can mix types. Add a type constraint
and PowerShell converts every element on the way in, or refuses:
$mixed = 'web01', 42, (Get-Date '2026-11-09'), $true
$mixed | ForEach-Object { $_.GetType().Name }
[int[]]$ids = '10', '20', '30'
$ids[0].GetType().NameString
Int32
DateTime
Boolean
Int32[int[]]$ids = '10', 'twenty'MetadataError: Cannot convert value "twenty" to type "System.Int32". Error: "The input string 'twenty' was not in a correct format."A typed array is a cheap way to validate input: the error happens at assignment, not three functions later.
Indexing and slicing
Indexes start at 0. Negative indexes count from the end, a range returns a slice, and a comma-separated list picks specific elements:
$servers = 'web01', 'web02', 'web03', 'db01', 'db02'
$servers[0]
$servers[-1]
$servers[1..3]
$servers[0, 2, 4]
$servers[-2..-1]web01
db02
web02
web03
db01
web01
web03
db02
db01
db02Reading past the end is not an error by default; you just get $null. Strict mode turns it
into one, which is a good reason to use strict mode in scripts:
$servers = 'web01', 'web02'
$servers[10]
$null -eq $servers[10]
Set-StrictMode -Version Latest
$servers[10]True
OperationStopped: Index was outside the bounds of the array.The negative range trap
To get "everything except the first element", $servers[1..-1] looks right. It is not.
1..-1 is the range 1, 0, -1, so you get the second, first and last elements:
$servers = 'web01', 'web02', 'web03', 'db01'
$servers[1..-1]web02
web01
db01Compute the end index, or let Select-Object do it:
$servers = 'web01', 'web02', 'web03', 'db01'
$servers[1..($servers.Count - 1)]
$servers | Select-Object -Skip 1web02
web03
db01
web02
web03
db01Arrays are fixed size
.NET arrays cannot grow. The .Add() method exists (arrays implement IList) but always
fails:
$servers = 'web01', 'web02'
$servers.Add('web03')MethodInvocationException: Exception calling "Add" with "1" argument(s): "Collection was of a fixed size."+= works because it does not grow the array. It creates a new array one element
longer, copies everything across, and points the variable at the copy. Removing works the
same way, by building a filtered copy:
$servers = 'web01', 'web02'
$servers += 'web03'
$servers -join ', '
$servers = $servers -ne 'web02'
$servers -join ', 'web01, web02, web03
web01, web03When a command returns one item
A command that returns several objects gives you an array. A command that returns exactly
one gives you that object, not an array of one. Most of the time you do not notice, because
PowerShell adds a .Count to single objects. Indexing is where it bites, because indexing a
string returns a character:
$errorLogs = Get-ChildItem ./logs -Filter 'error*.log' -Name
$errorLogs
$errorLogs.Count
$errorLogs[0]
$errorLogs = @(Get-ChildItem ./logs -Filter 'error*.log' -Name)
$errorLogs[0]error-2026-11-09.log
1
e
error-2026-11-09.logWrap the command in @( ) whenever you are going to index the result or rely on it being a
list. It costs nothing and removes a whole class of "works with two files, breaks with one"
bugs.
The += performance trap, measured
Because every += copies the whole array, building an array of N items with += does work
proportional to N squared. Here are three ways to collect 20,000 strings:
$n = 20000
$plus = Measure-Command {
$result = @()
foreach ($i in 1..$n) { $result += "item$i" }
}
$list = Measure-Command {
$result = [System.Collections.Generic.List[string]]::new()
foreach ($i in 1..$n) { $result.Add("item$i") }
}
$capture = Measure-Command {
$result = foreach ($i in 1..$n) { "item$i" }
}
'{0,-22}{1,8:N0} ms' -f '+= on an array', $plus.TotalMilliseconds
'{0,-22}{1,8:N0} ms' -f 'List[string].Add()', $list.TotalMilliseconds
'{0,-22}{1,8:N0} ms' -f 'loop output captured', $capture.TotalMilliseconds+= on an array 4,720 ms
List[string].Add() 166 ms
loop output captured 225 msThat was PowerShell 7.6.9 (a second run printed 2,662, 104 and 100 ms). The same script in Windows PowerShell 5.1 on the Windows host printed:
+= on an array 22,120 ms
List[string].Add() 106 ms
loop output captured 73 msYour numbers will differ, but the shape will not: += is 20 to 300 times slower here, and
the gap grows with N. Two rules follow:
- If a loop produces the items, assign the loop:
$result = foreach (...) { ... }. PowerShell collects whatever the loop outputs into an array for you. This is the simplest and usually the fastest option. - If you need to add and remove items over time, use a
List[T].
+= on a handful of items is fine; the gate script in the
previous article uses it for a
three-item problem list. Just do not use it on anything that scales with your input.
Generic lists: List[T]
System.Collections.Generic.List[T] is a resizable list of type T. Add really adds,
and it has the methods you would expect:
$queue = [System.Collections.Generic.List[string]]::new()
$queue.Add('web01')
$queue.AddRange([string[]]('web02', 'web03', 'db01'))
$queue.Count
$queue.Remove('web02')
$queue.Contains('db01')
$queue.Insert(0, 'lb01')
$queue -join ', '
$queue.RemoveAt(0)
$queue -join ', '4
True
True
lb01, web01, web03, db01
web01, web03, db01Remove returns True when it found the item. The type parameter is enforced, with the same
conversion rules as a typed array, so a List[int] accepts '8080' but not 'http':
$ports = [System.Collections.Generic.List[int]]::new()
$ports.Add('8080')
$ports.Add('http')MethodException: Cannot convert argument "item", with value: "http", for "Add" to type "System.Int32": "Cannot convert value "http" to type "System.Int32". Error: "The input string 'http' was not in a correct format.""Use List[object] if you need mixed types. Add using namespace System.Collections.Generic
at the top of a script and you can write [List[string]]::new().
You will see System.Collections.ArrayList in older scripts. It works, but its Add()
returns the new index, which leaks into your output:
$hosts = [System.Collections.ArrayList]::new()
$hosts.Add('web01')
$hosts.Add('web02')0
1Inside a function those numbers become part of the return value. Prefer List[T], whose
Add() returns nothing.
Hashtables
A hashtable maps keys to values. Lookups by key are fast no matter how many entries it holds, which makes hashtables the right tool for lookup tables, counters and configuration:
$ports = @{ http = 80; https = 443; postgres = 5432 }
$ports
Name Value
---- -----
https 443
http 80
postgres 5432
Notice the order: not the order you wrote. A plain hashtable does not keep insertion order,
and in PowerShell 7 the order is not even stable between sessions, because .NET randomises
string hash codes per process. When I re-ran this article's examples in fresh sessions, the
same hashtables listed their keys in a different order each time. Never rely on it; use
[ordered] (below) when order matters. Read values with an index or with dot notation:
$ports = @{ http = 80; https = 443; postgres = 5432 }
$ports['https']
$ports.postgres
$ports.Count443
5432
3Adding, updating and removing
Assigning to a key adds it or overwrites it. The .Add() method only adds, and throws if the
key exists, which is useful when a duplicate means a bug:
$ports = @{ http = 80; https = 443 }
$ports['redis'] = 6379
$ports.ssh = 22
$ports['http'] = 8080
$ports.Count
$ports.http
$ports.Add('https', 8443)4
8080
MethodInvocationException: Exception calling "Add" with "2" argument(s): "Item has already been added. Key in dictionary: 'https' Key being added: 'https'"The other everyday methods:
$ports = @{ http = 80; https = 443; redis = 6379 }
$ports.ContainsKey('redis')
$ports.ContainsValue(22)
$ports.Remove('redis')
$ports.Count
$ports['missing']
$null -eq $ports['missing']True
False
2
TrueA missing key returns $null rather than an error. That makes "does it exist?" ambiguous if
$null is a legitimate value, so use ContainsKey() when it matters. Keys are
case-insensitive by default: in @{ HTTP = 80 }, both $ports['http'] and $ports.Http
return 80.
Iterating: .Keys and GetEnumerator()
$ports = [ordered]@{ http = 80; https = 443; postgres = 5432 }
foreach ($key in $ports.Keys) { "$key -> $($ports[$key])" }
$ports.GetEnumerator() | ForEach-Object { '{0} listens on {1}' -f $_.Key, $_.Value }http -> 80
https -> 443
postgres -> 5432
http listens on 80
https listens on 443
postgres listens on 5432The pipeline is where hashtables surprise people. A hashtable goes down the pipeline as
one object, not one per entry. GetEnumerator() turns it into a stream of key/value
pairs that Sort-Object, Where-Object and friends can work with:
$ports = @{ http = 80; https = 443; postgres = 5432 }
($ports | Measure-Object).Count
($ports.GetEnumerator() | Measure-Object).Count
$ports.GetEnumerator() | Sort-Object Value -Descending | Select-Object -First 21
3
Name Value
---- -----
postgres 5432
https 443
Do not modify a hashtable while iterating it
Removing entries inside a foreach over .Keys fails, because the key collection changed
under the loop:
$ports = @{ http = 80; https = 443; telnet = 23 }
foreach ($key in $ports.Keys) { if ($ports[$key] -lt 100) { $ports.Remove($key) } }OperationStopped: Collection was modified; enumeration operation may not execute.Iterate over a copy of the keys instead. @( ) makes that copy:
$ports = @{ http = 80; https = 443; telnet = 23 }
foreach ($key in @($ports.Keys)) { if ($ports[$key] -lt 100) { $ports.Remove($key) } }
$ports.Keys -join ', 'httpsOrdered dictionaries
[ordered] creates an OrderedDictionary, which remembers insertion order and can also be
indexed by position:
$plain = @{ name = 'web01'; region = 'eu-west-1'; size = 'm5.large'; zone = 'b' }
$plain.Keys -join ', '
$ordered = [ordered]@{ name = 'web01'; region = 'eu-west-1'; size = 'm5.large'; zone = 'b' }
$ordered.Keys -join ', '
$ordered[1]zone, region, name, size
name, region, size, zone
eu-west-1Use [ordered] whenever the order will be seen by a human or written to a file: report
columns, JSON documents, configuration you will diff.
Counting with a hashtable
The most common real-world hashtable is a tally. Incrementing a missing key works, because
$null plus one is one. Here it counts log levels in an application log:
$counts = @{}
foreach ($line in Get-Content ./app.log) {
$level = (-split $line)[2]
$counts[$level]++
}
$counts
Name Value
---- -----
ERROR 2
WARN 2
INFO 5
(-split $line)[2] takes the third whitespace-separated field (see
-split).
Group-Object can do the same job, but the hashtable version is faster on big files and
easy to extend.
Nested hashtables for configuration
Values can be hashtables themselves, which gives you a per-environment configuration with a variable selecting the branch:
$config = @{
prod = @{ replicas = 6; region = 'eu-west-1' }
staging = @{ replicas = 2; region = 'eu-central-1' }
}
$config.prod.replicas
$config['staging']['region']
$stage = 'staging'
$config[$stage].replicas6
eu-central-1
2Splatting with hashtables
A hashtable whose keys are parameter names can be passed to a command with @ instead of $
(splatting, introduced in the previous article).
Its real value is building parameters conditionally, then making one call:
$includeArchive = $true
$search = @{
Path = './logs'
Filter = '*.log'
Name = $true
}
if ($includeArchive) { $search.Recurse = $true }
Get-ChildItem @searchapp.log
error-2026-11-09.log
archive/app-2026-11-01.logThe alternative, an if with two nearly identical Get-ChildItem lines, gets out of hand
as soon as there are three optional parameters. Splatting also keeps long command lines
readable, one parameter per line, without backtick line continuations.
Custom objects with [PSCustomObject]
A hashtable is a lookup table. When each item is a record (a server, a user, a result
row), you want an object with properties. Cast a hashtable literal to [PSCustomObject]:
$server = [PSCustomObject]@{
Name = 'web01'
Region = 'eu-west-1'
CPU = 4
Online = $true
}
$server
$server.CPU * 2
$server.GetType().Name
Name Region CPU Online
---- ------ --- ------
web01 eu-west-1 4 True
8
PSCustomObject
Properties keep the order you wrote them in, and the object displays as a row. Compare the same data as a hashtable, which displays as name/value pairs in hash order:
@{ Name = 'web01'; Region = 'eu-west-1'; CPU = 4 }
Name Value
---- -----
Region eu-west-1
CPU 4
Name web01
The real difference shows up with many records. An array of objects is a table, and every pipeline cmdlet understands it:
$fleet = @(
[PSCustomObject]@{ Name = 'web01'; Region = 'eu-west-1'; CPU = 4; MemoryGB = 16 }
[PSCustomObject]@{ Name = 'web02'; Region = 'eu-west-1'; CPU = 4; MemoryGB = 16 }
[PSCustomObject]@{ Name = 'db01'; Region = 'eu-central-1'; CPU = 16; MemoryGB = 128 }
)
$fleet
$fleet | Where-Object CPU -ge 8 | Select-Object -ExpandProperty Name
$fleet.Name -join ', '
($fleet | Measure-Object -Property MemoryGB -Sum).Sum
Name Region CPU MemoryGB
---- ------ --- --------
web01 eu-west-1 4 16
web02 eu-west-1 4 16
db01 eu-central-1 16 128
db01
web01, web02, db01
160
$fleet.Name is member enumeration: asking an array for a property returns that property
from every element.
Adding properties and methods
Unlike a hashtable, you cannot add a property just by assigning to it:
$server = [PSCustomObject]@{ Name = 'web01' }
$server.Owner = 'payments-team'SetValueInvocationException: Exception setting "Owner": "The property 'Owner' cannot be found on this object. Verify that the property exists and can be set."Add-Member adds note properties (plain values), script properties (computed on every read)
and script methods. Inside the script blocks, $this is the object:
$server = [PSCustomObject]@{ Name = 'web01'; CPU = 4 }
$server | Add-Member -NotePropertyName Owner -NotePropertyValue 'payments-team'
$server | Add-Member -MemberType ScriptProperty -Name Size -Value {
if ($this.CPU -ge 8) { 'large' } else { 'small' }
}
$server | Add-Member -MemberType ScriptMethod -Name Describe -Value {
"$($this.Name): $($this.Size), owned by $($this.Owner)"
}
$server
$server.Describe()
$server.CPU = 16
$server.Describe()
Name CPU Owner Size
---- --- ----- ----
web01 4 payments-team small
web01: small, owned by payments-team
web01: large, owned by payments-team
Size was recalculated after CPU changed, because a script property runs on every read.
When you want to add a property to a whole collection, Select-Object with a calculated
property is more idiomatic. It takes a hashtable with Name and Expression, and returns
new objects:
$fleet = @(
[PSCustomObject]@{ Name = 'web01'; Region = 'eu-west-1'; CPU = 4; MemoryGB = 16 }
[PSCustomObject]@{ Name = 'db01'; Region = 'eu-central-1'; CPU = 16; MemoryGB = 128 }
)
$fleet | Select-Object Name, CPU, @{ Name = 'GBPerCore'; Expression = { $_.MemoryGB / $_.CPU } }
$fleet | Select-Object -Property *, @{ Name = 'Environment'; Expression = { 'prod' } } | Format-List
Name CPU GBPerCore
---- --- ---------
web01 4 4
db01 16 8
Name : web01
Region : eu-west-1
CPU : 4
MemoryGB : 16
Environment : prod
Name : db01
Region : eu-central-1
CPU : 16
MemoryGB : 128
Environment : prod
Inspecting properties generically
Every object exposes its properties through .PSObject.Properties, which lets you write code
that works on any record without knowing its property names:
$server = [PSCustomObject]@{ Name = 'web01'; Region = 'eu-west-1'; CPU = 4 }
$server.PSObject.Properties.Name
foreach ($p in $server.PSObject.Properties) { '{0,-8}= {1}' -f $p.Name, $p.Value }Name
Region
CPU
Name = web01
Region = eu-west-1
CPU = 4Converting hashtables to objects
You often build data as a hashtable and want an object at the end. The cast works on a
hashtable variable too, but a plain hashtable has already lost its order by then. Cast an
[ordered] dictionary to keep it:
$settings = @{ Name = 'web01'; Region = 'eu-west-1'; CPU = 4 }
[PSCustomObject]$settings
[PSCustomObject][ordered]@{ Name = 'web01'; Region = 'eu-west-1'; CPU = 4 }
Name CPU Region
---- --- ------
web01 4 eu-west-1
Name Region CPU
---- ------ ---
web01 eu-west-1 4
The conversion matters most at export time. Here is a list of hashtables sent to
ConvertTo-Csv in Windows PowerShell 5.1:
$rows = @(
@{ Name = 'web01'; CPU = 4 }
@{ Name = 'db01'; CPU = 16 }
)
$rows | ConvertTo-Csv#TYPE System.Collections.Hashtable
"IsReadOnly","IsFixedSize","IsSynchronized","Keys","Values","SyncRoot","Count"
"False","False","False","System.Collections.Hashtable+KeyCollection","System.Collections.Hashtable+ValueCollection","System.Object","2"
"False","False","False","System.Collections.Hashtable+KeyCollection","System.Collections.Hashtable+ValueCollection","System.Object","2"5.1 exported the properties of the hashtable object itself. PowerShell 7 learned to treat dictionaries as rows, and the same lines in 7.6.9 printed:
"CPU","Name"
"4","web01"
"16","db01"Better, but the columns are in hash order, which changes between sessions (a later run gave
"Name","CPU"). Build [PSCustomObject] records and both versions agree, with your column
order every time.
Collections of objects to CSV and JSON
Arrays of objects map directly onto CSV rows and JSON arrays. Details of both formats are in CSV, JSON, and XML; these are the parts that trip people up with collections.
$rows = @(
[PSCustomObject]@{ Name = 'web01'; CPU = 4 }
[PSCustomObject]@{ Name = 'db01'; CPU = 16 }
)
$rows | Export-Csv ./fleet.csv
Get-Content ./fleet.csv
$imported = Import-Csv ./fleet.csv
$imported[1].CPU.GetType().Name"Name","CPU"
"web01","4"
"db01","16"
StringCSV has no types, so CPU comes back as a string; cast it before doing maths. Windows
PowerShell 5.1 also writes a #TYPE System.Management.Automation.PSCustomObject first line
unless you pass -NoTypeInformation; PowerShell 7 leaves it out by default.
ConvertTo-Json turns the same collection into an array of JSON objects:
$fleet = @(
[PSCustomObject]@{ Name = 'web01'; Region = 'eu-west-1'; CPU = 4 }
[PSCustomObject]@{ Name = 'db01'; Region = 'eu-central-1'; CPU = 16 }
)
$fleet | ConvertTo-Json[
{
"Name": "web01",
"Region": "eu-west-1",
"CPU": 4
},
{
"Name": "db01",
"Region": "eu-central-1",
"CPU": 16
}
]The trap is depth. ConvertTo-Json only serialises two levels deep by default:
$deploy = [PSCustomObject]@{
Service = 'checkout'
Targets = @(
[PSCustomObject]@{
Region = 'eu-west-1'
Hosts = @( [PSCustomObject]@{ Name = 'web01'; Ports = 80, 443 } )
}
)
}
$deploy | ConvertTo-JsonWARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.
{
"Service": "checkout",
"Targets": [
{
"Region": "eu-west-1",
"Hosts": ""
}
]
}The whole Hosts list became an empty string. PowerShell 7 at least warns; Windows
PowerShell 5.1 produced the same truncated JSON with no warning at all when I ran it.
Always pass -Depth for nested data (the maximum is 100):
$deploy | ConvertTo-Json -Depth 5 -Compress{"Service":"checkout","Targets":[{"Region":"eu-west-1","Hosts":[{"Name":"web01","Ports":[80,443]}]}]}Going the other way, ConvertFrom-Json produces PSCustomObjects, and in PowerShell 7
-AsHashtable gives you an ordered hashtable instead (handy when keys are not valid property
names or differ only by case):
$json = '{"service":"checkout","replicas":3,"regions":["eu-west-1","eu-central-1"]}'
$obj = $json | ConvertFrom-Json
$obj.regions[1]
$obj.GetType().Name
($json | ConvertFrom-Json -AsHashtable).GetType().Nameeu-central-1
PSCustomObject
OrderedHashtableComparing collections with Compare-Object
Compare-Object reports what is in one collection but not the other. The SideIndicator
says where: <= means only in the reference (first) set, => only in the difference
(second) set. A drift check of expected services against running ones:
$expected = 'nginx', 'redis', 'postgres', 'node-exporter'
$running = 'nginx', 'postgres', 'node-exporter', 'xmrig'
Compare-Object -ReferenceObject $expected -DifferenceObject $running
InputObject SideIndicator
----------- -------------
xmrig =>
redis <=
redis should be running and is not; xmrig, a cryptocurrency miner, is running and should
not be. Add -IncludeEqual to also list matches with ==:
$expected = 'nginx', 'redis', 'postgres'
$running = 'nginx', 'postgres', 'xmrig'
Compare-Object $expected $running -IncludeEqual
InputObject SideIndicator
----------- -------------
nginx ==
postgres ==
xmrig =>
redis <=
Compare objects by property
With objects, always tell Compare-Object which properties to compare. Here are two monthly
access exports compared without -Property:
$before = Import-Csv ./access-2026-10.csv
$after = Import-Csv ./access-2026-11.csv
Compare-Object $before $after
'(nothing above?)'(nothing above?)No differences reported, although a user was removed, one was added and one changed role.
Without -Property, the objects are compared by their string form, and a PSCustomObject
has none worth comparing. Windows PowerShell 5.1 gave the same empty result. With
-Property:
$before = Import-Csv ./access-2026-10.csv
$after = Import-Csv ./access-2026-11.csv
Compare-Object $before $after -Property User, Role
User Role SideIndicator
---- ---- -------------
bob admin =>
frank developer =>
bob developer <=
dave readonly <=
The output objects only carry the compared properties. -PassThru returns the original
objects instead, with SideIndicator added, so other columns such as Team survive:
$before = Import-Csv ./access-2026-10.csv
$after = Import-Csv ./access-2026-11.csv
Compare-Object $before $after -Property User -PassThru | Select-Object User, Role, Team, SideIndicator
User Role Team SideIndicator
---- ---- ---- -------------
frank developer payments =>
dave readonly finance <=
Comparing only on User finds joiners and leavers; adding Role also finds role changes.
Where you'll use this
Back to the access review from the start of the article. Two exports of production access, one per month:
User,Role,Team
alice,admin,platform
bob,developer,payments
carol,developer,payments
dave,readonly,finance
erin,admin,securityUser,Role,Team
alice,admin,platform
bob,admin,payments
carol,developer,payments
erin,admin,security
frank,developer,paymentsThe script compares them by user and role, turns the side indicators into words with a hashtable lookup, builds clean records, flags new admin grants, and exports the changes for the ticket:
# access-review.ps1 - what changed in production access since last month?
$before = Import-Csv ./access-2026-10.csv
$after = Import-Csv ./access-2026-11.csv
$labels = @{ '=>' = 'Granted'; '<=' = 'Revoked' }
$changes = Compare-Object $before $after -Property User, Role |
ForEach-Object {
[PSCustomObject]@{
User = $_.User
Role = $_.Role
Change = $labels[$_.SideIndicator]
}
} | Sort-Object User, Change
$changes | Format-Table -AutoSize
# admin grants need a second approver, so call them out
$adminGrants = @($changes | Where-Object { $_.Change -eq 'Granted' -and $_.Role -eq 'admin' })
"Admin grants needing approval: $($adminGrants.User -join ', ')"
$changes | Export-Csv ./access-changes.csv
$changes | ConvertTo-Json | Set-Content ./access-changes.json
"Wrote $($changes.Count) changes to access-changes.csv and access-changes.json"./access-review.ps1
Get-Content ./access-changes.csv
User Role Change
---- ---- ------
bob admin Granted
bob developer Revoked
dave readonly Revoked
frank developer Granted
Admin grants needing approval: bob
Wrote 4 changes to access-changes.csv and access-changes.json
"User","Role","Change"
"bob","admin","Granted"
"bob","developer","Revoked"
"dave","readonly","Revoked"
"frank","developer","Granted"Each structure has one job: arrays hold the rows, a hashtable translates codes to labels,
[PSCustomObject] gives every change the same shape so Sort-Object, Export-Csv and
ConvertTo-Json handle it, and @( ) keeps $adminGrants a list even with one match. The
same pattern covers configuration drift (desired versus actual settings), firewall rule
audits, package baselines and "which servers are missing from monitoring" checks.
Common mistakes
Calling .Add() on an array. Collection was of a fixed size. Use += for a few items,
assign the loop's output, or switch to [System.Collections.Generic.List[T]].
Removing hashtable entries inside a loop over .Keys. Collection was modified; enumeration operation may not execute. Loop over @($hash.Keys), a copy.
Exporting hashtables. In 5.1, $hashtables | Export-Csv writes IsReadOnly,
IsFixedSize and SyncRoot columns; in 7 the columns come out in hash order. Convert to
[PSCustomObject] first.
Nested data through ConvertTo-Json without -Depth. Anything below level two becomes
an empty string or a type name, with a warning in 7 and silently in 5.1.
Comparing objects without -Property. Compare-Object reports no differences between
two different sets of PSCustomObjects. Name the properties that define equality.
Passing $null to Compare-Object. When a query returns nothing, the variable is
$null, and the comparison stops:
$expected = 'nginx', 'redis'
$running = $null
Compare-Object $expected $runningCompare-Object: Cannot bind argument to parameter 'DifferenceObject' because it is null.Wrap the input in @( ), or default it with $running ?? @() (PowerShell 7). An empty
array compares fine and reports every expected item as <=.
Summary
@( )always produces an array; use it around any command whose result you will index or count, because a single result is not an array and'text'[0]is a character.- Negative indexes count from the end, but a range like
1..-1counts down through 0. Use$a[1..($a.Count - 1)]orSelect-Object -Skip. - Arrays are fixed size and
+=copies the whole array each time. Measured here: 4.7 s (PowerShell 7.6) and 22 s (5.1) for 20,000 items, against well under a second for aList[string]or for assigning the loop's output directly. - Hashtables are case-insensitive, unordered key/value maps (in PowerShell 7 the order can
differ between sessions). Assign to add or update,
.Add()to insist on a new key,ContainsKey()to test,GetEnumerator()to pipe the entries, and[ordered]to keep insertion order. [PSCustomObject]@{ ... }creates a record with ordered properties. Add members withAdd-MemberorSelect-Objectcalculated properties; plain assignment to a new property fails.- Export objects, not hashtables. Pass
-DepthtoConvertTo-Jsonfor nested data, and remember thatImport-Csvreturns strings. Compare-Objectmarks reference-only items<=and difference-only items=>; with objects, always pass-Property, and use-PassThruto keep the original objects.
Exercises
Create a hashtable with ssh = 22, http = 80, postgres = 5432. Add redis on 6379,
change http to 8080, check whether an https key exists, then print every entry sorted by
port number as aligned name port lines.
Show Solution
$services = @{ ssh = 22; http = 80; postgres = 5432 }
$services.redis = 6379
$services.http = 8080
$services.ContainsKey('https')
$services.GetEnumerator() | Sort-Object Value | ForEach-Object { '{0,-10}{1,5}' -f $_.Key, $_.Value }False
ssh 22
postgres 5432
redis 6379
http 8080Sorting needs GetEnumerator(), because the hashtable itself is a single pipeline object.
Sort-Object Value sorts the entries by their value.
Count how many times each status code appears in this list using a hashtable, and print the results sorted by code:
$codes = 200, 200, 404, 500, 200, 301, 404, 200, 503Show Solution
$codes = 200, 200, 404, 500, 200, 301, 404, 200, 503
$tally = @{}
foreach ($code in $codes) { $tally[$code]++ }
$tally.GetEnumerator() | Sort-Object Name | ForEach-Object { '{0}: {1}' -f $_.Key, $_.Value }200: 4
301: 1
404: 2
500: 1
503: 1$tally[$code]++ works on a missing key because the missing value is $null, and $null
incremented is 1. Name is an alias for Key on the enumerator's entries.
You received disk data as hashtables. Turn them into objects with Name, UsedPct (whole
percent) and Alert (true when 90% or more is used), and output the result as CSV.
$raw = @(
@{ Name = 'web01'; DiskGB = 100; UsedGB = 91 }
@{ Name = 'web02'; DiskGB = 100; UsedGB = 42 }
@{ Name = 'db01'; DiskGB = 500; UsedGB = 260 }
)Show Solution
$report = foreach ($r in $raw) {
[PSCustomObject]@{
Name = $r.Name
UsedPct = [math]::Round($r.UsedGB / $r.DiskGB * 100)
Alert = $r.UsedGB / $r.DiskGB -ge 0.9
}
}
$report | ConvertTo-Csv"Name","UsedPct","Alert"
"web01","91","True"
"web02","42","False"
"db01","52","False"Assigning the foreach to $report collects one object per iteration without +=, and
the explicit [PSCustomObject] fixes the column order.
Every server should have the baseline packages. Print only the packages that are in the baseline but not installed (ignore extra packages).
$baseline = 'curl', 'git', 'jq', 'openssh-server', 'rsync'
$installed = 'git', 'jq', 'netcat', 'openssh-server', 'curl'Show Solution
Compare-Object $baseline $installed | Where-Object SideIndicator -eq '<=' | Select-Object -ExpandProperty InputObjectrsyncReference-only items carry <=. netcat is reported as => and filtered out.
-ExpandProperty InputObject returns the bare package names rather than a table.
This collects every log line ending in 0 or 5 from 100,000 lines. Measure it, rewrite it
without +=, measure again, and confirm both versions collect the same number of lines.
$lines = 1..100000 | ForEach-Object { "2026-11-09 08:00:00 INFO request $_" }
$matched = @()
foreach ($l in $lines) { if ($l -match '[05]$') { $matched += $l } }Show Solution
$lines = 1..100000 | ForEach-Object { "2026-11-09 08:00:00 INFO request $_" }
$slow = Measure-Command {
$matched = @()
foreach ($l in $lines) { if ($l -match '[05]$') { $matched += $l } }
}
"slow: $($matched.Count) lines in $([int]$slow.TotalMilliseconds) ms"
$fast = Measure-Command {
$matched = foreach ($l in $lines) { if ($l -match '[05]$') { $l } }
}
"fast: $($matched.Count) lines in $([int]$fast.TotalMilliseconds) ms"slow: 20000 lines in 2347 ms
fast: 20000 lines in 484 msThe fast version outputs matching lines from the loop and lets PowerShell collect them.
Your timings will differ; when I ran this, the += version varied between runs, but it was
always several times slower, and the gap widens as the input grows. (Variables assigned
inside a Measure-Command block are visible afterwards because the block runs in the
current scope.)
Tested with: PowerShell 7.6.9 on Ubuntu 24.04 (WSL2) and Windows PowerShell 5.1
(5.1.26100) on Windows 11, November 2026. All examples were run as shown in PowerShell 7.6.9.
The 5.1 results (the hashtable CSV export, the silent JSON truncation, Compare-Object
without -Property, and the timing table) come from running the same code in
powershell.exe -NoProfile on the Windows host, in memory only. Timings are from single runs
and will vary on your machine; the ratios are the point.
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every PowerShell tutorial here is tested end to end before publishing.