Search PowerShellers and other PowerShell-related sites

Monday, November 10, 2008

-include and -exclude go together

While reading James Brundage's blog post Microcode: Exploring More of .NET with Get-Assembly, I have spotted a rather unnecessary complicated part of a code:

Get-ChildItem (Join-Path $env:Windir "Assembly") -recurse -filter "*.dll" |
Where-Object {
! $_.Name.Substring(0,$_.Name.IndexOf($_.Extension)).EndsWith(".ni")
}


The goal was to remove from the list of the DLLs those files named something like AssemblyName.Ni.Dll, because they cannot be loaded. At first I thought this is the right job for a -notlike operator:

Get-ChildItem (Join-Path $env:Windir "Assembly") -recurse -filter "*.dll" |
Where-Object {$_.name -notlike "*.ni.*"}


It'll do the job and it's much cleaner (and simpler).

On the other hand, Get-ChildItem has an -exclude parameter. It must be faster than piping to Where-Object. Why not use that instead? To my surprise the combination of -filter and -exclude parameters produced totally wrong result.

Fortunately, Get-ChildItem has an -include parameter too, which can be used instead of a -filter in this case (hat tip to Joel 'Jaykul' Bennett). So, the final command is:

Get-ChildItem (Join-Path $env:Windir "Assembly") -recurse -include "*.dll" -exclude "*.ni.*"


Isn't that easier to write (and probably faster to execute)?