Convert String to Int in PowerShell

Convert String to Int in PowerShell

Using Dynamic Casting

Use dynamic casting to convert the given string to int in PowerShell.

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:

Using [Convert]::ToInt32() Method

Use [Convert]::ToInt32() method to convert the specified string to int in PowerShell.

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 than Int32.MaxValue or less than Int32.MinValue.

Using [int]::Parse() Method

Use [int]::Parse() method to convert the specified string to integer.

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 is null.
  • 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 than Int32.MaxValue or less than Int32.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.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *