PowerShell for Windows Admins

Jul 7 2017   8:03AM GMT

Variable as a where clause

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

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.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: