for vs foreach vs "foreach"
Reading Time: Approximately 4 minutes.
Many developers and sysadmins starting out with Powershell will assume that this:
$arr = 1..10
$arr2 = @()
foreach ($num in $arr) { $arr2 += $num + 1 }
write-output $arr2
is the same as this:
$arr = 1..10
$arr2 = @()
for ($i = 0; $i -lt $arr.length; $i++) { $arr2 += $arr[$i] + $i }
write-output $arr2
or this:
$arr = 1..10
$arr2 = @()
$arr | foreach { $arr2 += $_ + 1 }
Just like those Farmers Insurance commercials demonstrate, they are not the same. It’s not as critical of an error as, say, mixing up Write-Output
with Write-Host
(which I’ll explain in another post), but knowing the difference between the two might help your scripts perform better and give you more flexibility in how you do certain things within them.
You’ll also get some neat street cred. You can never get enough street cred.
… »