Multi Variable Assignment in Powershell

February 6, 2008 at 4:02 AMAndy Schneider

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.

Posted in:

Tags:

Comments (2) -

Alexwebmaster
Alexwebmaster says:

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

Reply

what about some photo's?

Reply

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading