Where-Object: Just A Pipeline-Aware If-Clause

Where-Object is one of the most frequently used PowerShell commands, yet it looks unfamiliar to new PowerShell users. Those who are familiar with the “SQL” database query language can use Where-Object like the Where statement in SQL clauses: it is a client-side filter that eliminates unwanted items. This line would take all services and display only those who are actually running:

Get-Service | Where-Object { $_.Status -eq "Running" }

To better understand how Where-Object works, it is basically an If-Clause for the pipeline. The above code is the equivalent of this:

Get-Service | ForEach-Object {
    if ($_.Status -eq 'Running')
    { $_ }
}

Or, in a completely pipeline-free “traditional” approach:

$services = Get-Service
Foreach ($_ in $services)
{
  if ($_.Status -eq 'Running')
  {
    $_
  }
}

psconf.eu – PowerShell Conference EU 2019 – June 4-7, Hannover Germany – visit www.psconf.eu There aren’t too many trainings around for experienced PowerShell scripters where you really still learn something new. But there’s one place you don’t want to miss: PowerShell Conference EU – with 40 renown international speakers including PowerShell team members and MVPs, plus 350 professional and creative PowerShell scripters. Registration is open at www.psconf.eu, and the full 3-track 4-days agenda becomes available soon. Once a year it’s just a smart move to come together, update know-how, learn about security and mitigations, and bring home fresh ideas and authoritative guidance. We’d sure love to see and hear from you!

Twitter This Tip! ReTweet this Tip!

GD Star Rating
loading...