Powershell

How to convert string to integer in PowerShell

PowerShell can detect the data type independently. But it can be problematic, as sometimes PowerShell cmdlets return an integer while the variable type is a string. As a result, we can not compare it with another integer value. That is why we use the PowerShell cmdlets to get the data type of a certain value. Similarly, it will be easier to convert a string to an integer when you know the exact data type of a certain value.

This post will illustrate the method to resolve the mentioned query.

How to Convert String to an Integer Value in PowerShell?

We can convert string values into integers easily when we know their data type. So, first, let’s get the data type of an integer and string.

Below the examples are given for fetching the data types of certain values.

Example 1: Check Numbered Value Data Type
In this example, we will first check the data type of the given number “76” with the help of the “GetType()” function and display the “Name” property value:

$a=76
$a.GetType().Name

In the above code:

  • First, we have assigned the value “76” to a variable “$a”.
  • After that, invoke “GetType().Name” to fetch the data type of the created variable:

It can be observed that the specified variable is of “Int32” integer type:

Example 2: Get the Data Type of the String Value
Let’s examine the data type of the given value “76” that is stored as a string:

$a="76"
$a.GetType().Name

Output

Example 3: Convert String to an Integer
Finally, let’s convert a string to an integer in PowerShell. For that purpose, see the below demonstration:

$a="76"
$a = $a -as [int]
$a.GetType().Name

In the above code:

  • First, we have assigned stored the string “76” in the “$a” variable:
  • After that, we assigned the “$a -as [int]” to the variable “$a” to convert a string to an integer.
  • -as” parameter is used here to convert a string to an integer:

Output

The output confirms that the string value has been converted to an integer value.

Conclusion

To convert a string to an integer, first, assign a string value to a variable. After that, write the variable, along with the “-as” parameter, and then write the “[int]” to convert the string to an integer. This tutorial has demonstrated a full procedure for converting a string to an integer in PowerShell.

About the author

Muhammad Farhan

I am a Computer Science graduate and now a technical writer who loves to provide the easiest solutions to the most difficult problems related to Windows, Linux, and Web designing. My love for Computer Science emerges every day because of its ease in our everyday life.