How to convert the Integer variable to the string variable in PowerShell?

To convert the integer variable to the string variable, you need to use the explicit conversion or the functional method. In the below example, we are assigning an integer value to the variable $X.

$x = 120

Now when you check the data type of that variable, it will be Int32.

To convert it into the string variable, first, we will use the explicit method by using a square bracket and data type to convert inside the brackets.

[string]$x = 130

The data type of $x is the String.

In the second method, you can use the PowerShell functional method ToString() to convert. For example,

$x = $x.ToString()

In the same way, you can convert string value to the integer value but in its defined range. For example,

$x = "123"
[int]$x = $x

Here, we are declaring “123” as the string variable and to convert it we will use [int] data type ahead of $x so it will be converted to an integer variable. But when you convert a character string into an integer, you will get an error.

For example,

$x = "abc"
[int]$x = $x

Cannot convert value "abc" to type "System.Int32". Error: "Input string was not in a correct format."
At line:1 char:1
+ [int]$x = $x
+ ~~~~~~~~~~~~
+ CategoryInfo : MetadataError: (:) [], ArgumentTransformationMetadataException + FullyQualifiedErrorId :RuntimeException