Monthly Archives: June 2010

foreach executes code unexpectedly

Tags :

Category : Gotcha , Windows PowerShell

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:

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):

So take care 😉