Register : : Login
menuleft menuright
submenu
 
Dec 2

Written by: Oisin Grehan
12/2/2007 4:18 PM  RssIcon

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:

 
  1. $arr = @(1,2,3,$null,5)  
  2.  
  3. $arr | where-object { $_ -ne $null } | foreach-object { $_

Then, using a traditional VBScript style, using the foreach keyword, as opposed to the foreach-object cmdlet:

 
  1. $arr = @(1,2,3,$null,5)  
  2.  
  3. foreach ($elem in $arr) {  
  4.     if ($elem -ne $null) {  
  5.         $elem 
  6.     }  

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:

 
  1. $arr = @(1,2,3,$null,5)  
  2.  
  3. foreach ($elem in $arr | where-object {$_} ) {  
  4.     $elem 

As Mr. Snover is fond of saying, this is a great example of PowerShell's pithiness. PithyShell at its best!

 
Blogs
  
Search Blogs
  
Archives
  
   
footer Sponsored by Quest Software • SAPIEN Technologies • Compellent • Microsoft Windows Server 2008 R2 footer
footer