PS – filtering with many conditions

Hello all.

In many times we have to create more than only one condition to filter the outcome of a result. This produces a lot of unnecessary code and ends up in a bloated code as we can see in this example:

Get-WMIObject Win32_LogicalDisk -filter "DriveType = 3" -ComputerName $computer -ErrorAction SilentlyContinue | 
%{Get-ChildItem ('\\' + $computer + '\' + ($_.DeviceID).remove(1) + '$\*') -File *.doc,*.docx -Recurse -Force -ErrorAction SilentlyContinue | 
?{($_.fullname -notmatch "Windows") -and ($_.fullname -notmatch "Program Files") -and ($_.fullname -notmatch "Program Files (x86)")} |
Add-Content $env:TEMP\$computer.txt

This can be simplified by using Regex. In Regex the pipe “|” means the operation “or”. So we can concat a lot of conditions by using the pipe in the matching string. But be careful. You have to escape every character which is defined in Regex.

This can also be done with the “Escape” function from the Regex class:

[Regex]::Escape($string)

By using this the following code can be compressed

?{($_.fullname -notmatch "Windows") -and ($_.fullname -notmatch "Program Files") -and ($_.fullname -notmatch "Program Files (x86)")}

to this

?{($_.fullname -notmatch "Windows|Program Files|Program Files \(x86\)") 

And more complex esclusions can be added to a hashtable to get an better overview.

$exclusions=@(
"Windows"
"Program Files"
"Program Files (x86)"
)

$exclusions=($exclusions -join "|").Replace('(','\(').Replace(')','\)')

?{($_.fullname -notmatch $exclusions) 

Have fun by using this little trick.

~David

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s