Skip navigation

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.
Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish