PowerShell Cannot Convert Value to Type System.Int32 (Fixed)

My restock script died on the first row of a Columbus store’s inventory CSV with “Cannot convert value to type System.Int32”. It means PowerShell tried to turn a value into a whole number and couldn’t.

The quickest safe fix is to test the conversion first:

$qty = 0
if ([int]::TryParse($value, [ref]$qty)) { $qty } else { "Not a number: '$value'" }

In this tutorial, I’ll show you what causes cannot convert value to type system.int32 in PowerShell, how to find the bad value, and which fix to use for text, big numbers, arrays and user input.

Quick answer: inspect the value, then clean it, use [long], or convert with -as [int] or TryParse.

What does “Cannot convert value to type System.Int32” mean?

System.Int32 is the .NET type behind [int]. It holds whole numbers from -2,147,483,648 to 2,147,483,647. You get the error when a cast, a typed variable or a typed parameter receives something that isn’t one:

$qty = '12 boxes'
$total = [int]$qty * 4

Output (PowerShell 7):

InvalidArgument: C:\psfaqs\err.ps1:2
Line |
   2 |  $total = [int]$qty * 4
     |  ~~~~~~~~~~~~~~~~~~~~~~
     | Cannot convert value "12 boxes" to type "System.Int32". Error: "The input string '12 boxes' was not in a correct
     | format."
PowerShell 7 console showing Cannot convert value 12 boxes to type System.Int32 with InvalidArgument
The [int] cast fails on the text 12 boxes (PowerShell 7)

The text after Error: is the real reason. Windows PowerShell 5.1 words it a little differently and adds the error ID InvalidCastFromStringToInteger:

Windows PowerShell 5.1 console showing Cannot convert value to type System.Int32 and InvalidCastFromStringToInteger
Same error, older wording, plus CategoryInfo and FullyQualifiedErrorId (Windows PowerShell 5.1)

The label MetadataError means the same failure on a variable declared as [int]$retries. A brief look at PowerShell data types helps if [int], [long] and [double] are new to you.

Find the value that breaks the conversion

Look at the value first. Brackets reveal hidden spaces, and GetType() shows whether it’s a string, number or array:

$qty = '12 boxes'
"Value: [$qty]"
"Type:  $($qty.GetType().FullName)"
"Whole number? $($qty -match '^\s*[-+]?\d+\s*$')"

Output:

Value: [12 boxes]
Type:  System.String
Whole number? False

The value is a String with a word in it, so it can’t become an Int32. This guide to getting an object’s type shows more ways to inspect a variable.

Cause 1: The string has text, unit