Sunday, July 15, 2012

Supporting Wildcard Pattern Matching in Script CMDLETS

One of the cool features about PowerShell is its support for POSIX style patterns in many of the pre-installed cmdlets. For example the following command will get all items under the C root that have the second, third and forth characters “rog”:

Outputs:

    Directory: C:\


Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d-r--          6/7/2012  11:30 PM            Program Files
d-r--         6/26/2012   1:50 PM            Program Files (x86)

The following table shows a reference of the supported POSIX style matching patterns:

Wildcard character

Description

Example

Matches

Does not match

*

Matches zero or more characters, starting at the specified position

a*

A, ag, Apple

 

?

Matches any character at the specified position

?n

An, in, on

ran

[ ]

Matches a range of characters

[a-l]ook

book, cook, look

took

[ ]

Matches the specified characters

[bc]ook

book, cook

look

So how would one go about adding support for these types of patterns in a script CMDLET? In order to do this you’ll need to work with two .NET types:

  1. System.Management.Automation.WildcardPattern
  2. System.Management.Automation.WildcardOptions

First define your options (Compile, CultureInvariant, IgnoreCase or None). Then use New-Object to create a WildcardPattern instance using the pattern you want to match against as the first argument and the WildcardOptions object as the second argument.

Here is a an example function: