header image

Variable type

Posted by: | August 18, 2018 Comments Off on Variable type |

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
PS> $x = ‘now a string’
PS> $x
now a string


If you give the variable an explicit type

PS> [int]$x = 35
PS> $x
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


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.

under: PowerShell

Comments are closed.