Convert String to Integer in PowerShell

Rohan Timalsina Dec 21, 2022 Dec 29, 2021
  1. Use [int] to Convert String to Integer in PowerShell
  2. Define the Data Type of a Variable to Convert String to Integer in PowerShell
Convert String to Integer in PowerShell

This tutorial will teach you to convert strings to integers in PowerShell.

Use [int] to Convert String to Integer in PowerShell

Let us consider that we have a variable $a as shown below.

$a = 123

The data type of $a is an integer.

$a.GetType().Name

Output:

Int32

But when you enclose the value with " ", the data type will become string.

$b = "123"
$b.GetType().Name

Output:

String

To convert such string data type to integer, you can use [int] as shown below.

$b = $b -as [int]
$b.GetType().Name

Output:

Int32

Define the Data Type of a Variable to Convert String to Integer in PowerShell

PowerShell can detect the data type of a variable on its own.

You don’t need to be specific about the data type and declare a variable. But, you can define the data type of a variable before it so that you can force the data type.

For example:

[int]$c = "456"
$c.GetType().Name

Output:

Int32

If you try to force an integer data type to a string value, you will get an error.

[int]$data = "storage"

Output:

Cannot convert value "storage" to type "System.Int32". Error: "Input string was not in a correct format."
At line:1 char:1
+ [int]$data = "storage"
+ ~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : MetadataError: (:) [], ArgumentTransformationMetadataException
    + FullyQualifiedErrorId : RuntimeException
Rohan Timalsina avatar Rohan Timalsina avatar

Rohan is a learner, problem solver, and web developer. He loves to write and share his understanding.

LinkedIn Website

Related Article - PowerShell String