foreach executes code unexpectedly
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
Friday, 25. June 2010 10:15
That is why you shouldn’t blindly evaluate, but also use If ($Element -is [object]) {…} blocks…