Dec
2
Written by:
Oisin Grehan
12/2/2007 4:18 PM
It's very easy sometimes to look at the PowerShell grammar and partition it into two distinct styles: pipeline and traditional imperative script. In fact, it took a number of weeks of playing around before I realised that this is leaving out a large portion of patterns that employ a fusion of these two styles. For example, Let's iterate over an array of numbers, skipping null elements; first, using the pipeline style:
- $arr = @(1,2,3,$null,5)
-
- $arr | where-object { $_ -ne $null } | foreach-object { $_ }
Then, using a traditional VBScript style, using the foreach keyword, as opposed to the foreach-object cmdlet:
- $arr = @(1,2,3,$null,5)
-
- foreach ($elem in $arr) {
- if ($elem -ne $null) {
- $elem
- }
- }
And finally, a fusion of the two styles whereby I insert a pipeline into the expression, and also take advantage of the fact that $null will evaluate to $false, thereby skipping the need to test with the -eq operator:
- $arr = @(1,2,3,$null,5)
-
- foreach ($elem in $arr | where-object {$_} ) {
- $elem
- }
As Mr. Snover is fond of saying, this is a great example of PowerShell's pithiness. PithyShell at its best!
Tags: