You may not have noticed this, but the -Filter parameter on Get-ChildItem (aka dir or ls) is not as specific as you think. The following line should only find PowerShell scripts, but in fact it finds a lot more:

Get-ChildItem -Path $env:windir -Filter *.ps1 -Recurse -ErrorAction Silent |
  Group-Object -Property Extension -NoElement 

Here is the result:

 
Count Name                     
----- ----                     
  800 .ps1                     
  372 .ps1xml 
 

The -Filter parameter mimics the behavior found in the old-fashioned “dir” command. To really have specific results, this is the code you should use instead:

Get-ChildItem -Path $env:windir -Filter *.ps1 -Include *.ps1 -Recurse -ErrorAction SilentlyContinue |
  Group-Object -Property Extension -NoElement

Here is the correct result:

 
Count Name                     
----- ----                     
  800 .ps1   
 

While you could omit the -Filter parameter, it is strongly recommended you keep it. First of all, -Include works only in combination with -Recurse, and secondly, -Include is slow. By doing a rough (but fast) first filtering with -Filter, then a second filtering with -Include, you are best off.

Are you an experienced professional PowerShell user? Then learning from default course work isn’t your thing. Consider learning the tricks of the trade from one another! Meet the most creative and sophisticated fellow PowerShellers, along with Microsoft PowerShell team members and PowerShell inventor Jeffrey Snover. Attend this years’ PowerShell Conference EU, taking place April 17-20 in Hanover, Germany, for the leading edge. 35 international top speakers, 80 sessions, and security workshops are waiting for you, including two exciting evening events. The conference is limited to 300 delegates. More details at www.psconf.eu

Twitter This Tip! ReTweet this Tip!

Anonymous