Topic: Setting Multiple Variables at the Same Time
Notice: This post is a part of the PowerShell Monday series — a group of quick and easy to read mini lessons that briefly cover beginning and intermediate PowerShell topics. As a PowerShell enthusiast, this seemed like a beneficial way to ensure those around me at work were consistently learning new things about Windows PowerShell. At some point, I decided I would share these posts here, as well. Here’s the PowerShell Monday Table of Contents.
Welcome to the first PowerShell Monday.
Let’s get started: The first example shows one way to set, or assign, a value to a variable in Windows PowerShell. In this example, $p is assigned the string value ‘Welcome to Monday’.
$p = 'Welcome to Monday.'
Knowing that, what do you think this command accomplishes?
$a = $b = $c = 'string' # Answer further below… # Keep going… # Keep going… # Keep going…
After running that command, here are the values stored in $a, $b, and $c.
# The command was $a = $b = $c = 'string'. $a $b $c string string string
A command such as this, although not often seen, sets all three variables to the same value. Knowing this in an option, allows us to initialize a group of variables to the same value, at the same time. While you can do this in three separate commands, as the next two examples show, you can complete the same thing, as part of a single command.
# The line break is a command separator in PowerShell. $x = 'string' $y = 'string' $z = 'string'
# The semicolon is a command separator, too. $x = 'string'; $y = 'string'; $z = 'string'
Bonus: What do you think this command does?
$m,$n,$o = 'string'
You probably won’t ever see this command — I haven’t — but why not know what it does. In this example, only $m is assigned the value of ‘string’. The other two — $n and $o, in this example — lose any value they may have been storing. Again, I haven’t seen this, and I wouldn’t recommend you use it. I suspect that it would end up being confusing, compared to the traditional methods of assigning and removing values from variables. I said it was a bonus; I didn’t say it was a useful.
Second Bonus: What about this command; what do you think happens here?
$e,$f,$g = 'Monday','Tuesday','Wednesday'
I’ve never seen this command used either, but I can see how this one might be useful to use, without too much confusion. I still won’t recommend it, though. In this example, we end up assigning ‘Monday’ to $e, ‘Tuesday’ to $f, and ‘Wednesday’ to $g. If we had a fourth variable, such as $h, and it had a value in it, the value would be removed, such as we saw in the first bonus. This is of course, unless there was another value after ‘Wednesday’.
That’s it for the first PSMonday. Hope you’ve learned something new, and we’ll do this again next week.