Multi Variable Assignment in Powershell

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.

Comments (2) -

Alexwebmaster 3/3/2009 11:03:32 AM

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

what about some photo's?

Comments are closed