Using RegEx to Filter Files

by Jul 7, 2013

Get-ChildItem supports basic wildcards, but it does not support the rich feature set of regular expressions. If you combine Get-ChildItem with Where-Object, you can easily add this functionality.

This example lists all DLL files found in System32 folder that start with "a" and have a name of exactly 6 characters:

$pattern = '^a(.{5})\.dll$'
Get-ChildItem $env:windir\system32\*.dll | Where-Object { $_.Name -match $pattern } 

And this minor change would find all files with a name length between 4 and 6 characters:

$pattern = '^a(.{3,5})\.dll$'
Get-ChildItem $env:windir\system32\*.dll | Where-Object { $_.Name -match $pattern }

Regular expressions can do a lot more. Either search for one of the zillions of tutorials found for free in the Internet, or as a quick start, enter this:

Note that on PowerShell 3.0, this requires that you downloaded the help files first using Update-Help.

Twitter This Tip! ReTweet this Tip!