0

I would like to implement some custom cmdlets that filter some object by name, and I would like to use wild-card enabled search like for common cmdlets (Get-ChildItem and Get-Process).

How can I implement this kind of search? Are there some examples or even some reusable components? Any examples?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
fra
  • 3,488
  • 5
  • 38
  • 61

2 Answers2

1

For the most part, these types of cmdlets leverage the WildcardPattern class.

Here's an example of how to use it directly from the PowerShell prompt:

PS>$w = New-Object System.Management.Automation.WildcardPattern "*foo*"
PS>$w.IsMatch("foobar")
True
PS>$w.IsMatch("barbar")
False
0

You can define your own filter by piping a collection of objects to Where-Object (or the short-form ?).

For example, if you get a collection of file objects by doing gci (alias of Get-ChildItem), you can display only the ones that have the text log in them by doing this: gci | ?{$_.name -match "log"}.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
SpellingD
  • 2,533
  • 1
  • 17
  • 13
  • Thanks for the suggestion, but I would like to implement it within the cmdlet because I would like to filter data accessed in a database. – fra Apr 23 '12 at 13:24
  • Some cmdlets have filters (gci -filter "query"), but the filters are based upon the provider (for gci, it would be the filesystem provider) and aren't actually defined within the cmdlets themselves. – SpellingD Apr 23 '12 at 14:24
  • What @SpellingD means is that you would use the value of $Filter directly on your database query (after sanitizing it of course!). – JasonMArcher May 03 '12 at 18:31