Understanding Foreach and Foreach-object in Powershell

Foreach and Foreach-object are subject of discussion lately and we have a word for it. Looping is the core of any code or script and we have to make sure to do it correctly. But ever wonder which one fits better to run certain codes on multiple servers. Let’s check this out in this post and grab some useful knowledge. 

Head to Head: Foreach-object and Foreach

Foreach is one of the rising-star when chosen between invoke-command and where { }.
The advantage of having foreach is that we can store value under one string in excel which is a boon. Likewise, we get 2 different options while choosing foreach (), 1 is foreach itself and the other is foreach-object. But when you see the object it looks similar doesn’t it.
Well I have performed a test so that we can pick our winner.
 
ForEach-Object is best used when sending data through the pipeline because it will continue streaming the objects to the next command in the pipeline, for example.

Speed Test between Foreach-object and Foreach

Test Code below: This will test how much time it actually takes for the loops to complete.

				
					$a=Get-ChildItem –File C:\users\dhrub\ -Recurse
$time = (Measure-Command {

   $a | ForEach-Object {

        $_

    }

}).TotalMilliseconds

 [pscustomobject]@{

    Type = 'ForEach-Object'

    Time_ms = $Time

 }
 $Time = (Measure-Command {

    ForEach ($i in ($a)) {

        $i

    }

}).TotalMilliseconds

  [pscustomobject]@{

    Type = 'ForEach'

    Time_ms = $Time

 }
 
 Output:
 
 Type            Time_ms
----            -------
ForEach-Object 213.3006
ForEach         64.8013
				
			

The Output will surely shock you !

Unable to delete unwanted software or software don't get cleaned up fully ?

Special Uninstaller is a great application to delete or uninstall software that is not required. The plus point is it clears every file and registry key associated with the application. It is available for Free and Premium with 24×7 support. Do try this application out.

The Verdict: Which to use?

The ForEach statement loads all of the items upfront into a collection before processing them one at a time. 

ForEachObject expects the items to be streamed via the pipeline, thus lowering the memory requirements, but at the same time, taking a performance hit.

Forach will be always faster than Foreach-object but this doesn’t determine you don’t use foreach-object. It always depends upon the requirement of the work.

Related Posts

Leave a Reply

Please disable your adblocker or whitelist this site!