PowerShell: Convert String to Integer

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 Variable 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.

powershell convert string to int

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

powershell string to int

Hint. Other popular data types in PowerShell:

  • [string]

  • [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] — an 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

convert string to int powershell

Hint. Also, you can face this error when trying to concatenate an integer value with a string.

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

Or:

$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):

$integerN2 =[convert]::ToInt32($stringN)

You can also use the methods of the System.Convert class to convert to various PowerShell data types. A complete list of available data type conversions can be displayed as follows:

[System.Convert] | Get-Member -Static|select name

powershell convert to int

As you can see, the methods of the System.Convert class allows you to convert a value not only to Int32, but also to other integer data types:

  • Int16 — Signed 16-bit integer (short);
  • Int64 — Signed 64-bit integer (long);
  • UInt32 — Unsigned 32-bit integer (uint);
  • UInt64 — Unsigned 64-bit integer (ulong);
  • Etc.

powershell convert string to number

To convert a string to an Int32 value, run the following command:

[System.Convert]::ToInt32($stringN)

The convert method also allows you to convert numeric data to different number systems.

This syntax is used:

[Convert]::ToInt32(value, notation)

For example, you want to convert a value from binary string format to integer. In this case, you need to specify 2 as the second parameter of the method (the decimal number notation is used by default, so 10 can be omitted):

$a="100"

[System.Convert]::ToInt32($a,2)

Any of these methods convert the String variable to System.Int32 type.

Check for Integer Input in PowerShell Scripts

In some cases, when you get the value of a variable from the user or any other source, you need to check if the input is an integer value. You can use the following PowerShell function to validate integer input in PowerShell scripts. This function takes a value as input and checks if it corresponds to the Integer32 data type (after conversion)

Function IsInteger ([string]$vInteger)

{

    Try

    {

        $null = [convert]::ToInt32($vInteger)

        return $True

    }

    Catch

    {

        return $False

    }

}

You can check the correctness of the function on the test data:

IsInteger("one")

IsInteger("23.2")

IsInteger(100)

IsInteger("100")

powershell string to number

I enjoy technology and developing websites. Since 2012 I'm running a few of my own websites, and share useful content on gadgets, PC administration and website promotion.
Latest posts by Cyril Kardashevsky (see all)

One comment

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.