Quick Loop

by Jun 23, 2015

Requires PowerShell 4.0

There are plenty of looping constructs in PowerShell. Here is a rather unusual way introduced in PowerShell 4.0 to repeat code. This example will play a sound with an increasing frequency (make sure you enable your speakers):

(1..100).Foreach{[Console]::Beep($_ * 100, 300)}

In PowerShell 4.0 and better, arrays now have the methods Where() and Foreach(). You can write a filter like this:

@(Get-Service).Where({$_.Status -eq 'Running'})

As a special syntactical rule, when you use these methods, you can omit the parenthesis, too:

@(Get-Service).Where{$_.Status -eq 'Running'}

Note that this approach requires an array of values. In comparison to a traditional pipeline, this approach is much faster at the expense of a much higher memory consumption.

Twitter This Tip! ReTweet this Tip!