PowerShell v3: Simplified.

In PowerShell v1 and v2, here's how you got a list of running services:

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

If you were a real pro, you might shorten all that:
Gsv | Where { $_.Status -eq 'Running' }

It was always a bit confusing to newcomers. Why the curly brackets? Answer: They enclose executable code, and PowerShell executes that code to see if each piped-in object meets your criteria. If the code returns True, it sends the object down the pipeline. If not, the object is dropped.

Why the $_? That was especially vexing for newbies. Answer: It represents the piped-in object(s), so that you have a way to refer to them in your comparison criteria. 

In v3, the above syntax still works - and you'll need to use it for more complex comparisons. But for simple comparisons, this will now work:
Get-Service | Where Status -eq 'Running'

Wow. A lot easier. This doubtless took a ton of work on the PowerShell team's part, to make this work with the command-line parser, but it sure is easier for newcomers. ForEach-Object gets a similarly-simplified syntax, and continues to supports its old syntax as well.

Of course, this is all subject to my standard PowerShell v3 caveat - keep in mind we're dealing with pre-release code.

Discuss this Blog Entry 2

on Sep 22, 2011
I would say it's even easier that that - because pattern is just positional argument you do not need to quote it: Get-Process | where Name -like *power* ls | where Name -match ^test.* Gotta love that. ;)
on Sep 28, 2011
I'm so in the habit of quoting strings (blame VBScript) that I often forget that - thanks for the reminder, Bartek!

Please or Register to post comments.

What's PowerShell with a Purpose Blog?

Don Jones demystifies Windows PowerShell.

Blog Archive

Sponsored Introduction Continue on to (or wait seconds) ×