Startsidan  ▸  Texter  ▸  Teknikblogg

Anders Hesselbom

Programmerare, skeptiker, sekulärhumanist, antirasist.
Författare till bok om C64 och senbliven lantis.
Röstar pirat.

Type safety in PowerShell

2009-01-11

Good or bad, here are some attributes of the PowerShell type system:

Variables are declared when they are first used. Just assign a value to a variable, and the variable is created if it doesn’t exist. The variables are not type safe. Try typing $x=10 followed by $x=”Hello” and you will see that $x is happy to change type for you, without complaining. However, by specifying the type before the name of the variable, you cannot assign a value of a different type without specifying the new type.

Start by assigning an integer value to a variable, and specify the variable type in front of the variable name.

[int]$i=10

If you try to assign a different integer value to the variable $i, PowerShell will accept it.

$i=20

But if you try to assign a string value to $i, it will not work because $i only accept integer values.

$i=”Hello” #Will not work

Whenever you like, you can change the type of a variable, by specifying a new type in front of it.

[string]$i=”Hello” #Works fine – the type of $i is changed

Names are not case sensitive, so this rather poor formatted iteration will run:

FOR($x=0;$x -lt 10;$X++) { Write-Host $x }

Notice that For and FOR is the same thing, that $x and $X is the same variable, and that the curly brackets are required, even though there is only one statement that is iterated here.

Categories: PowerShell

Leave a Reply

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



En kopp kaffe!

Bjud mig på en kopp kaffe (20:-) som tack för bra innehåll!

Bjud på en kopp kaffe!

Om...

Kontaktuppgifter, med mera, finns här.

Följ mig

Twitter Instagram
GitHub RSS

Public Service

Folkbildning om public service.

Hem   |   linktr.ee/hesselbom   |   winsoft.se   |   80tal.se   |   Filmtips