Enumerating and filtering
Enumerating, or listing, the objects in a collection in PowerShell does not need a specialized command. For example, if the results of Get-PSDrive
were assigned to a variable, enumerating the content of the variable is as simple as writing the variable name and pressing Return:
PS> $drives = Get-PSDrive $drives Name Used (GB) Free (GB) Provider Root ---- --------- --------- -------- ---- Alias Alias C 319.37 611.60 FileSystem C:\ Cert Certificate \ Env Environment ...
ForEach-Object
may be used where something complex needs to be done to each object.
Where-Object
may be used to filter results.
The ForEach-Object command
ForEach-Objec
t is most often used as a loop (of sorts). For example, the following command works on each of the results from Get-Process
in turn:
Get-Process | ForEach-Object {
Write-Host $_.Name -ForegroundColor Green
}
In the preceding example...