Monthly Archive


foreach usage

I’ve noticed the way foreach is being used and it falls into two groups. I am using foreach-object to keep the discussion straight – like everyone else I use the foreach alias – yes I know I rant about aliases but the aliases for the *-object cmdlets make sense.

$things = Get-Content some_file.txt
foreach ($thing in $things){
    ## do stuff here

Get-Content some_file.txt | foreach-object{
    ## do stuff here


The first one reads the file and then iterates through the objects while second one reads the file and puts the objects on the pipeline.

So whats the difference and is it a big deal?  Instinctively I try to use the second but is that best?

using foreach we have to read the file and hold all the objects in memory while the foreach-object works with them one at a time as they come down the pipeline – for a big file that makes a lot of difference in resources.  However, if we need to access a file multiple times using foreach may be the better option as we only have to read the file once.  foreach can be faster which is a trade off we may need to think about

inside the loops we can use $thing or $_ to access the object respectively.  One point to think about is that if you do further work inside the loop that generates a different $_ eg a switch then reading the code may get confusing especially if you come back to it after a while

So is there a best option – probably not as an all time categorical “this is the best so always use it”

I tend to prefer the foreach-object as I can get on with processing objects straightaway though we do have to be careful with subsequent order of events sometimes.  The other advantage is that foreach-object gives me a –begin, –process and –end script block which makes things even more flexible

So no hard and fast answer but as a final thought the foreach-object usage looks more “powershelly” as someone once put it

Technorati Tags: PowerShell,foreach

One Response to foreach usage

Leave a Reply