Monthly Archive

Categories

PowerShell foreach

PowerShell has a number of ways to perform a loop – I recently counted seven distinct methods. If you can’t list them all don’t worry one is very esoteric and unexpected. I’ll enumerate them in a future post. For now I want to concentrate on a source of confusion – especially to newcomers to PowerShell – namely the PowerShell foreach statements.

The confusion arises because there are effectively two foreach statements. One is a PowerShell keyword that initiates a loop and the other is an alias for  a cmdlet.

Lets start with the foreach loop.

$numbers = 1..10
foreach ($number in $numbers){
  [math]::Pow($number, 2)
}

foreach in this case is used to iterate over a collection. In the example above $numbers is an array of numbers 1 to 10. Foreach number in the array it is raised to the power 2 – squared.

Remember that PowerShell is unique among shells in that you can use pipelines in many places that other languages insist on variables so you could change the example to

foreach ($number in 1..10){
  [math]::Pow($number, 2)
}

The array is generated and then iterated over as earlier.

If you see foreach as the first command on a line you’re dealing with the foreach keyword and therefore a loop.

On the other hand if you see foreach in a pipeline

1..10 | foreach {
  [math]::Pow($_, 2)
}

or

1..10 | foreach {
  [math]::Pow($psitem, 2)
}

you’re dealing with the cmdlet. $_ or $psitem denote the object currently on the pipeline. foreach is an alias for the Foreach-Object cmdlet and you’re using –Process as a position parameter for the scriptblock. Written in full you’re doing this

1..10 | ForEach-Object -process {
  [math]::Pow($_, 2)
}

or

1..10 | ForEach-Object -process {
  [math]::Pow($psitem, 2)
}

Just to add to the confusion you also have the option to use the foreach method on the collection

(1..10).foreach({[math]::Pow($psitem, 2)})

This isn’t seen as much though it should be remembered as this is the fastest way to iterate over a collection.

In summary

foreach starting a line is the looping keyword. Faster than the pipeline but increases memory overheads as  the collection has to pre-generated

foreach on the pipeline is an alias for foreach-object. Lower memory requirements as the collection is passed down the pipeline but a bit slower

().foreach({}) is a method on the collection (we treat it as an operator in PowerShell in Action) and is fast but in terms of coding style may be more intuitive to developers than admins.

Comments are closed.