Declaring multiple variables

In PowerShell, variables are created when they are first used. Just by assigning a value to a variable, that variable is created.

$x = 4

If you assign a different kind of value to that same variable, the type of the variable is changed.

$x = 4
Write-Output $x.GetType()
$x = "Hello"
Write-Output $x.GetType()

To lock a variable to a desired type, you can specify the type on the line where the variable is created. Now, this will fail, because “Hello” is a string value, not an integer.

[int]$x = 4
Write-Output $x.GetType()
$x = "Hello" #fails here!
Write-Output $x.GetType()

However, you can still change the type, if you declare the new type. This change to line 3 will make the code run again:

[int]$x = 4
Write-Output $x.GetType()
[string]$x = "Hello" #Success!
Write-Output $x.GetType()

Multiple variables can be created in one line of code. The first line will assign 1 to $a, 2 to $b and 3 to $c.

$a, $b, $c = 1, 2, 3
Write-Output $a
Write-Output $b
Write-Output $c

If you want type checking enforced on these variables, the type name are added next to each variable.

[int]$a, [int]$b, [int]$c = 1, 2, 3
Write-Output $a
Write-Output $b
Write-Output $c

The output is:

1
2
3

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *