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.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.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 = $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.