Traditional Loops
# The standard foreach
foreach ($server in $servers) {
Write-Output "Pinging $server..."
# Test-Connection -ComputerName $server -Count 1
}
# The standard for-loop
for ($i = 0; $i -lt 5; $i++) {
Write-Output "Loop $i"
}
Pipeline Filtering (Where-Object)
When data flows through the pipeline, use Where-Object (alias ?) to dynamically filter objects. Inside the filter, $_ or $PSItem represents the current object crossing the pipeline.
# Get all services. Filter WHERE the Status property equals "Stopped"
Get-Service | Where-Object { $_.Status -eq "Stopped" }
# Advanced filtering: Find specific processes consuming over 1GB memory!
Get-Process | Where-Object { $_.WorkingSet -gt 1GB -and $_.ProcessName -notmatch "chrome" }