PowerShell for Windows Admins

Aug 18 2018   6:03AM GMT

Variable type

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Tags:
Powershell

Usually when you create a variable you implicitly set the type by the value you use. Sometimes though you may want to explicitly set the variable type.

if you don’t give the variable a type you can do this:

PS> $x = 35
PS> $x
35
PS> $x = ‘now a string’
PS> $x
now a string

If you give the variable an explicit type

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

The variable expects an integer or something that can be converted to an integer

PS> $x = ‘123’
PS> $x
123

You can’t supply a type when you use New-Variable so if you need a read only or constant variable then create it as shown above then use Set-Variable to make it read only or constant.

 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: