r/PowerShell • • Dec 07 '19

PowerShell Traps - Collection of PowerShell traps and oddities

https://github.com/nightroman/PowerShellTraps
118 Upvotes

8 comments sorted by

View all comments

11

u/da_chicken Dec 07 '19

Here's more:

  1. An array on the left hand side of a logical operator with a scalar on the right will filter, not compare. @(1,2,3) -eq 2 will return 2, not false. This most commonly comes up when you want to check if a variable is null. Therefore, best practice is to always put $null on the left hand side.

  2. Arrays and strings are immutable in .Net. That means the += operator for both data types causes a tremendous amount of memory pressure as the entire object needs to be recreated.

Compare the execution time:

Measure-Command {
$x = 1..100000
$y = foreach ($i in $x) { $i }
}

Measure-Command {
$x = 1..100000
$y = @()
foreach ($i in $x) { $y += $i }
}