PowerShell Where | ForEach | -Filter
Where
Gathers information | uses the Where-Object for filtering; the $_. allows object oriented property selection of the property "Name"; then uses a comparison operator "-like" against a string with a wildcard *
​
​
#====================================================================================
# Pull informaiton and then add Where Condition that can be written in a few ways
#====================================================================================
Get-Service | Where-Object{$_.Name -like "We*"} | Select Name, Status
write-Output ""
Get-Service | Where{$_.Name -like "We*"} | Select Name, Status
write-Output ""
Get-Service | ?{$_.Name -like "We*"} | Select Name, Status
Foreach
​
Gather the information first and then loop through in a foreach loop with a conditional If
​
#=========================================================================
# Pull information and then loop through searching for service name
#=========================================================================
$MyServices=Get-Service | Select Name
Foreach($Service in $MyServices){
If ($Service.Name.StartsWith("We")){
write-output $Service.Name
}
}
-Filter
​
Filtering is a way to gather the data your require but isn't always available on all Cmdlets.
For example you cannot filter on Get-Service.
​
Get-ADuser -Filter {(name -like "Ste*") -and (Enabled -eq $True)} | Select Name, SamAccountName
​
Get-ADCOmputer -Filter {(name -like "My*") -and (Enabled -eq $True)} | Select Name
List all the CmdLets filter can be used with