Using Dynamic Casting
Use dynamic casting to convert the given string to int in PowerShell.
|
1 2 3 4 5 6 |
$string = "456" $number = [int]$string $number $number.GetType().Name |
|
1 2 3 4 |
456 Int32 |
First, we created and initialized a $string variable; then, we specified the type as [int] before the string variable to do dynamic casting. In dynamic casting, we tell the compiler to think about things differently.
To cross-check, we saved this converted value in the $number variable with which we chained GetType() to access its Name property, which denotes that we have successfully converted the $string to a number.
Remember, dynamic casting does not change the original variable’s data type ($string in this case) unless we replace it.
We can also use the -AS option as follows:
|
1 2 3 4 5 6 |
$string = "456" $intType = [int] $number = $string -AS $intType $number.GetType().Name |
|
1 2 3 |
Int32 |
Using [Convert]::ToInt32() Method
Use [Convert]::ToInt32() method to convert the specified string to int in PowerShell.
|
1 2 3 4 5 |
$string = "456" $number = [Convert]::ToInt32($string) $number.GetType().Name |
|
1 2 3 |
Int32 |
The [Convert]::ToInt32($string) command converted the value of $string to 32-bit signed integer. Here, the ToInt32() method belongs to a .NET class named [Convert], which provides different methods for converting data types. Similar to the previous example, we also chained the GetType() method with $number to get its Name property to see that we have successfully converted the given string to an integer.
We can get FormatException or OverflowException exception based on the following reasons:
FormatException– It occurs if the given string argument does not have an optional sign followed by a sequence of digits (0-9).OverflowException– Occurs when the specified string argument represents a number greater thanInt32.MaxValueor less thanInt32.MinValue.
Further reading:
Using [int]::Parse() Method
Use [int]::Parse() method to convert the specified string to integer.
|
1 2 3 4 5 6 |
$string = "456" $number = [int]::Parse($string) $number $number.GetType().Name |
|
1 2 3 4 |
456 Int32 |
For this example, we used a static method named Parse() of the [int] .NET framework class to convert the given string representation of a number to its 32-bit signed integer equivalent. The Parse() method returns a few exceptions for some reasons that are given below:
ArgumentNullException– Occurs if the given string variable isnull.FormatException– We get this exception if the string variable is not in the correct format.OverflowException– Occurs if the string variable represents a number greater thanInt32.MaxValueor less thanInt32.MinValue.
Finally, we accessed the Name property of the GetType() method to know that we have successfully converted the $string to $number.
That’s all about how to convert String to Int in PowerShell.