An extremely powerful feature (that isn’t all that well known) is the ability to assign values to multiple variables in one line. Take the following example:

PS> $one,$two,$three = "first","second","third"
PS> $one;$two;$three
first
second
third

This technique can be used in custom functions to parse the $args value

PS> function show-greeting {$greeting,$name = $args; "Hello $name, $greeting"}
PS> show-greeting "Nice to meet you" "Andy"
Hello Andy, Nice to meet you

One last thing to note is what happens if you have more values than variables. Does it blow up. An error. Not really. Check this out

PS C:\Users\andys> $one,$two = "first","second","third",4
PS C:\Users\andys> $one
first
PS C:\Users\andys> $two
second
third
4
PS C:\Users\andys> $one.count
PS C:\Users\andys> $two.count
3
PS C:\Users\andys>

The last variable gets the remaining values assigned to it.

3 Responses to “Multi Variable Assignment in Powershell”
  1. [...] check out my post on multi variable assignment to see how this [...]

  2. [...] Assign multiple variables in one expression (Get-PowerShell blog). Andy gets all the air time today. [...]

  3. Alexwebmaster says:

    Hello webmaster
    I would like to share with you a link to your site
    write me here preonrelt@mail.ru

Leave a Reply