
π This article includes 2 downloadable practice files β
In this article
Writing enterprise-grade automation scripts requires structuring data in memory and controlling program logic flow. PowerShell provides native support for dynamic variables, indexed arrays, associative hash tables, and structured control loops.
Basic Level: Variables and Dynamic Arrays
All variable names in PowerShell start with a dollar sign $. Variable names are case-insensitive and can hold any .NET object type.
# Declaring variables
= "app-prod-01"
= 8080
=
# Creating and indexing arrays
= @("web01", "web02", "db01", "cache01")
# "web01"
# "cache01" (last item)
.Count # 4
Intermediate Level: Hash Tables and Custom Data Objects
A hash table (dictionary/key-value store) is created using @{ key = value } syntax. Hash tables provide instant (O(1)) key lookups and are the cleanest way to pass parameters via Splatting.
# Hash table definition
= @{
ID = 1042
Name = "Rahul Sharma"
Department = "Finance"
Active =
}
# Parameter Splatting: cleaner code without huge single-line parameter flags
= @{
Path = "C:Reports2026-Q3.xlsx"
Destination = "\backup-serverFinance"
Force =
Verbose =
}
Copy-Item @copyParams # Notice the '@' symbol when splatting!
Looping Constructs: ForEach vs foreach-object
PowerShell provides two primary ways to iterate through collections:
# 1. Statement loop: 'foreach ( in )' β Fastest for in-memory arrays
= @("Apple", "Banana", "Orange")
foreach ( in ) {
Write-Host "Processing ..." -ForegroundColor Green
}
# 2. Pipeline loop: ' | ForEach-Object { }' β Best for streaming large streams
Get-Process | ForEach-Object {
if (.CPU -gt 50) {
Write-Warning "High CPU process: $(.Name) ($(.CPU)s)"
}
}
Expert Level: Type-Safe Generic Lists for High Performance
When appending thousands of items to a standard array using += , PowerShell creates a brand new array in memory every single iteration, causing severe (O(n^2)) performance degradation. For enterprise datasets, always use the .NET [System.Collections.Generic.List[T]]:
# High-performance generic list
= [System.Collections.Generic.List[PSObject]]::new()
1..10000 | ForEach-Object {
.Add([PSCustomObject]@{
Index =
Timestamp = (Get-Date)
Status = "OK"
})
}
Write-Host "Constructed $(.Count) objects instantly without array recreation!"
π Practice files for this article
β¬ Download all 2 files (ZIP Β· 592 B)
- π₯οΈps-04-variables-loops.ps1Lesson code file.β¬ PS1 Β· 323 B
- πps-04-variables-loops-output.txtOutput from our test run.β¬ TXT Β· 103 B
Free to use for learning. Files with macros (.bas) are plain text β import them with Alt+F11 β File β Import File, and always test on a copy.
Stuck on a step? Ask a question and the AI answers using this article.