Supporting Wildcards in PowerShell functions

In my last post I had a function called Get-TfsWorkItem and really needed to be able to easily search based on one property of the [WorkItem] object, in this case it was title. What I needed was some kind of wildcard support in my function. Sure I could pipe it to Where-Object but that gets old, especially if I am going to be using this thing every day. So I was thinking, why not put the where directly in the function and make the back half of the where clause a parameter.

Here’s the function again:

   1: function Get-TfsWorkItem {
   2: param($title = "*",
   3:       $user="Andy Schneider",
   4:       $Project='InfrastructureAutomation'
   5:       )  
   7: $WIQL = @"
  10: "@
  12: $tfs = Get-TfsServer 
  13: $workItems = $tfs.wit.query($WIQL)
  14: return $workItems | where {$_.Title -like $title}
  15: return $tfs
  16: }

Notice on line 14, rather than returning $workItems, I return $workitems piped to a where-object cmdlet that puts some condition on $workitem.Title.

That condition is specified as a parameter and defaults to * making the where-object cmdlet let everything pass. But if you wan to use it for something liket Get-TfsItem –title *PowerShell* you can, rather than doing get-tfsworkitem | where {$_.Title –like *powershell*}

You can obviously still filter on stuff later on in the pipeline, but it just gives a nice user experience, in my humble opinion.

Comments are closed