Thursday, April 20, 2017

A subtle difference between PowerShell ForEach and ForEach-Object

This blog post explains the major differences between PowerShell's ForEach statement and ForEach-Object cmdlet. There is a subtle difference, however, not mentioned in the post.

ForEach statement will not loop into a $null array variable, while ForEach-Object cmdlet will loop it once with a $null value. This may bite you with NullExceptions.

Here is a code snippet to demonstrate the issue.
$myArray = $null
# No loop
ForEach($i in $myArray){
'In ForEach'
$i
}
# Loop once with $null value
$myArray | ForEach-Object {
'In ForEach-Object'
$_
}
view raw ForEachDiff.ps1 hosted with ❤ by GitHub