Friday, August 21, 2015

PowerShell: Set Multiple Variables at Once

A list of variable names can be an l-value, that is, an expression that appears on the left side of an assignment operator. Did you know that you could do this…
PS C:\> $FirstName, $Initial, $LastName = 'John', 'Q', 'Public'
This statement will assign each variable the corresponding value on the right of the assignment operator. What if the number of variable names and values doesn’t match? Extra values will be stored as an array in the last variable, so in
PS C:\> $FirstName, $Initial, $LastName = 'John', 'Q', 'Public', 'Sr', 'Esq'
that $LastName variable will be a list containing Public, Sr, and Esq. If there aren’t enough values, the extra variable names are unassigned.
Oh, and if you want to set several variable names to the same value, use this:
PS C:\> $a = $b = $c = $d = 90
Have fun with your variables. Be seeing you.

No comments:

Post a Comment