If you’re new to PowerShell and want to build your scripting and automation skills, understanding how to work with arrays and loops is essential. In this beginner-friendly tutorial, we explore how to use PowerShell arrays and the foreach loop to automate repetitive tasks—perfect for anyone working in Windows environments or building their IT skills.
What Is an Array in PowerShell?
An array is a list of values or objects. You can use arrays to store things like file names, user accounts, or running processes. Arrays are useful when you need to perform the same action on multiple items.
# Simple array example:
$servers = 'Server1', 'Server2', 'Server3'
Looping with foreach
The foreach loop lets you iterate through each item in an array and perform actions on them. It’s one of the most beginner-friendly ways to handle looping in PowerShell.
# Foreach example with array:
foreach ($server in $servers) {
Write-Host "Checking status of $server"
}
Bonus Tip: The Array Subexpression Operator @()
Sometimes, PowerShell returns a single object when you expect an array—especially when filtering results. That’s where the array subexpression operator @() comes in. It forces the result to be treated as an array, even if it contains only one item.
# Array using the subexpression operator:
$processes = @(Get-Process | Where-Object { $_.CPU -gt 100 })
Without @(), if only one process matches, $processes won’t behave like an array. With @(), it always does—making your loops and logic more reliable.
What You’ll Learn in the Video
- Creating arrays in PowerShell
- Using foreach to loop through array items
- Real-world examples of automation using loops
- How and when to use the array subexpression operator
- Tips for writing clean, efficient scripts
Links:
A Beginner’s Guide to the AZ-900
https://www.udemy.com/course/beginners-guide-az-900/?referralCode=C74C266B74E837F86969
Zero to Hero with Azure Virtual Desktop
https://www.udemy.com/course/zero-to-hero-with-windows-virtual-desktop/?referralCode=B2FE49E6FCEE7A7EA8D4
Hybrid Identity with Windows AD and Azure AD
https://www.udemy.com/course/hybrid-identity-and-azure-active-directory/?referralCode=7F62C4C6FD05C73ACCC3
Windows 365 Enterprise and Intune Management
https://www.udemy.com/course/windows-365-enterprise-and-intune-management/?referralCode=4A1ED105341D0AA20D2E
PowerShell Commands
https://github.com/tsrob50/CiraltosTools