foreach executes code unexpectedly

Line Break

Author: Frank-Peter (77 Articles)

Hello again, Frank-Peter here.

The other day, one of my PowerShell training participants stumbled upon an issue with foreach: if you try to run a foreach loop against an empty variable whose type isn’t array the loop will execute the code once. This can be demonstrated easily either in PowerShell 1.0 or 2.0 with the $null variable:

PS C:\Test> foreach ($element in $null) {write-host "element: $element"}
element:
PS C:\Test>

In that case I’d expect that foreach doesn’t execute any code meaning that foreach should treat an empty or undefined non-array variable as same as an empty array variable (like shown below):

PS C:\Test> foreach ($element in @()) {write-host "element: $element"}
PS C:\Test>

So take care ;-)

Bookmark and Share
Tags »

Author:Frank-Peter
Date: Thursday, 24. June 2010 17:33
Trackback: Trackback-URL Category: Uncategorized

Feed for the post RSS 2.0 Comment this post

1 Comment

  1. 1

    That is why you shouldn’t blindly evaluate, but also use If ($Element -is [object]) {…} blocks…

Submit comment

CAPTCHA Image CAPTCHA Audio
Refresh Image