Tuesday, July 15, 2008

Filter in PowerShell

I was reading yesterday about filters in PowerShell - I noticed it in one script and didn't play with it before, so I was really curious...

This reading help about filters (Get-Help about_Filter -Detailed), I was getting more and more excited.

I understood that you can specify complex filters here, something like

Filter MyCustomFilter {
$_.ProcessName -match '^a.*'
$_.CPU -gt 20
}


Get-Process | Where {MyCustomFilter}



That would be really cool, because that you could easily provide filtering in some XML definition.



 



Obviously I didn't get it right. After studying a while PowerShell in Action (best book about PowerShell for me, highly recommended), I realized that Bruce is using filter to alter data:



PS (1) > filter double {$_*2}
PS (2) > 1..5 | double
2
4
6
8
10



Consider following filter:



Filter StartWithA {$_.ProcessName -match '^a.*'}



It should be able to filter all processes and display only ones that starts with a.



If we try to use it Get-Process | StartWithA, we will get array of booleans:



PS C:\Links\HDDs\DevHDD\WorkingProjects\S4Maintenance> gps | StartWithA
True
True
True
False
False
False
False
False
False
False
False
False
...



If we try to use Get-Process | Where{StartWithA}, we don't get anything in return.



If we use change this filter to



Filter StartWithA {$_ | Where {$_.ProcessName -match '^a.*'}}



then we finally get what we wanted:




PS C:\Links\HDDs\DevHDD\WorkingProjects\S4Maintenance> Get-Process | StartWithA | Select Name

Name
----
AcroRd32
alg
audiodg



It appears to be bug in PowerShell documentation - however it would be great if we could see filter as array of conditions in v2 ;)



Thanks to Mow for {$_ | Where {$_...}} example

No comments: