Skip to content

/errors/powershell/cannot-convert-value-to-type

Cannot convert value "abc" to type "System.Int32". Error: "Input string was not in a correct format."

verified onenvironmentlocal · windows 10.0.26200 arm64 · GNU bash 5.3.15 (Git Bash)updated
tool
PowerShell
exit code
1
versions
Windows PowerShell 5.1, PowerShell 7.x
os
windows, linux, macos

Cannot convert value "abc" to type "System.Int32". Error: "Input string was not in a correct format." means a cast ([int]'abc'), a typed variable or a typed parameter received a value PowerShell cannot convert. The inner error explains why: for numbers the string is not numeric; for dates, String was not recognized as a valid DateTime. Check the value, then convert it safely with -as or an explicit parse format.

Reproduce it

powershell
$ErrorActionPreference = 'Stop'
foreach ($sb in { [int]'abc' }, { [datetime]'31/12/2026' }, { [int]$n = 5; $n = 'five' }, { Get-ChildItem -Depth 'two' }) {
  try { & $sb } catch { $_.Exception.Message }
}

Output

Cannot convert value "abc" to type "System.Int32". Error: "Input string was not in a correct format."
Cannot convert value "31/12/2026" to type "System.DateTime". Error: "String was not recognized as a valid DateTime."
Cannot convert value "five" to type "System.Int32". Error: "Input string was not in a correct format."
Cannot bind parameter 'Depth'. Cannot convert value "two" to type "System.UInt32". Error: "Input string was not in a correct format."

Casts use the invariant culture, so [datetime]'31/12/2026' fails even on a machine whose regional format is day/month/year; [datetime]'2026-12-31' (ISO 8601) works everywhere.

Convert safely

powershell
'abc' -as [int]
"null from -as: $($null -eq ('abc' -as [int]))"
$n = 0
"TryParse('42'): $([int]::TryParse('42', [ref]$n)) -> $n"
[datetime]::ParseExact('31/12/2026', 'dd/MM/yyyy', [cultureinfo]::InvariantCulture).ToString('yyyy-MM-dd')
[int]' 42 '
[int]'1,024'.Replace(',', '')

Output

null from -as: True
TryParse('42'): True -> 42
2026-12-31
42
1024
NeedUse
Number or $null, no exception$value -as [int]
Test and convert[int]::TryParse($s, [ref]$n)
Date in a known format[datetime]::ParseExact($s, 'dd/MM/yyyy', [cultureinfo]::InvariantCulture)
Size strings like 10MBPowerShell numeric literal 10MB, or parse the number and multiply

Sources