Tuesday, March 6, 2018

PowerShell assignment can unpack arrays into variables

I was surprised to learn a few days ago that PowerShell can assign multiple variables in one expression:

$a, $b = 1, 2

As expected, that puts 1 into $a and 2 into $b. It turns out such syntax works with nonliteral arrays on the right:

$numbers = @(1, 2)
$a, $b = $numbers

Having more variables on the left than there are elements in the array assigns null to the extra variables.

No comments:

Post a Comment