Variable as a where clause

A post on the forum about using a variable as a where clause looked interesting. What the user wanted to do was to define a variable that contained the filter to be used by Where-Object.

As an example consider filtering the output of Get-Service to display only services that are stopped

PS> Get-Service | where Status -eq "Stopped"

You have to revert to the old style syntax

PS> Get-Service | where {$_.Status -eq "Stopped"}

The answer then becomes to create a scriptblock for the filter

PS> $filter = {$_.Status -eq "Stopped"}

 PS> Get-Service | where $filter

You could then use the filters like this

function gs {
  param (
   [string]$status
  )

switch ($status){
    "Running" {$filter = {$_.Status -eq "Running"}; break} 
    "Stopped" {$filter = {$_.Status -eq "Stopped"}; break} 
    default   {$filter = {$_.Status -like "*"}; break} 

 }

Get-Service | where $filter
}

PS> gs -status Running
PS> gs -status stopped
PS> gs -status *

If you need a variable as a where clause then use a scriptblock.

Advertisements
This entry was posted in Powershell. Bookmark the permalink.

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