Typing variables

I was recently asked a question about typing variables after thinking about it came up with this demonstration.

Create a variable with an integer value

£> $a = 2
£> $a.GetType()

IsPublic IsSerial Name
——– ——– —-
True     True     Int32

AS you would expect – you get an integer type.

If you do this

£> $a = ‘123’
£> $a.GetType()

IsPublic IsSerial Name
——– ——– —-
True     True     String

It changes to a string. Which means you can also do this.

£> $a = ‘gdyegf’
£> $a.GetType()

IsPublic IsSerial Name
——– ——– —-
True     True     String

PowerShell variables will adapt their type to the data they contain.

However if you type the variable:

£> [int32]$b = 2
£> $b.GetType()

IsPublic IsSerial Name
——– ——– —-
True     True     Int32

You start with an integer as expected

If you use a string that can be converted to an integer – that will happen and your type is still an integer.
£> $b = ‘123’
£> $b
123
£> $b.GetType()

IsPublic IsSerial Name
——– ——– —-
True     True     Int32

If you try to put a string in the variable

£> $b = ‘effAG’
Cannot convert value “effAG” to type “System.Int32”. Error: “Input string was not in a correct format.”
At line:1 char:1
+ $b = ‘effAG’
+ ~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException
    + FullyQualifiedErrorId : RuntimeException

It fails because you can’t convert  ‘effAG’ to an integer.

Untyped PowerShell variables can change their type. If you want to ensure the variable always contains a specific type then force that by typing the variable.

Advertisements
This entry was posted in Powershell Basics. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s