PowerShell for Windows Admins

Feb 15 2015   3:27AM GMT

Typing variables

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

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.

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: