Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.
2012-02-25
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
Categories: PowerShell
Tags: Variables
Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!
Leave a Reply