PowerShell belongs to a dynamic, not strongly typed language class. This means you don’t need to declare variables and set specific data types before using them. When you create a variable, you don’t need to specify its type: PowerShell will try to figure it out on its own.
How to Convert String to Integer in PowerShell?
When performing various actions on a variable, PowerShell can automatically determine the variable type, but this doesn’t always work well and correctly. Recently, we faced a problem: the PowerShell cmdlet returns a number in a variable of String type. As a result, we cannot compare it with another variable of type Integer. In this article, we will look at how to set the type of a PowerShell variable and convert a string value to an integer.
For example, let’s create a simple variable and check its type using the GetType () method:
$a = 1 $a.GetType()
PowerShell automatically assigned the type Int32 (Integer) to this variable.
$b = "1" $b.GetType()
If you set the value of a variable in quotation marks, PowerShell assumes it’s a string and returns a String type for it.
You can specify both the type of the variable and the type of the value. The following commands will create a variable containing a numeric value:
[int]$number = 1 $number.GetType().FullName $number1 = [int]1 $number1.GetType().FullName
Hint. Other popular data types in PowerShell:
[char] — ASCII character code
[bool] — “True” or “False”;
[int] — 32-bit number;
[long] — 64-bit number;
[decimal] — a floating point number of 128 bits and a d at the end;
[double] — 8 bit floating point number;
[single] — 32 bit floating point number;
[DateTime] — Powershell datatype storing date and time;
[array] — PowerShell array;
[hashtable] — hash table;
[pscustomonject] — array of type key and value.
If you try to assign a string value to a numeric variable or try to perform other numeric operation, you get an error:
[int]$number = 'Test'
Cannot convert value “Test” to type “System.Int32”. Error: “Input string was not in a correct format.” ArgumentTransformationMetadataException
Let’s say you have a variable containing a string (type System.String):
$stringN = “777” $stringN.GetType().FullName
The easiest way to convert a value to System.Int32 is to assign its value to a new variable with a declared data type:
$integerN = [int]$stringN
$integerN = [int]::Parse($stringN)
You can also use the -as operator:
$integerN1 = $stringN -as[int]
Or convert the data type using the ToInt32 method of the Convert class (the second argument of the Toint32 class specifies the number system):
Any of these methods converts the String variable to System.Int32 type.
- How to Setup Gmail in Outlook? - October 14, 2021
- How to Clear Browsing History in Safari on iPhone/iPad? - October 11, 2021
- Allow Non-administrators to Install Printer Drivers via GPO - October 1, 2021