PowerShell Type Casting and Type Conversion Examples

PowerShell Type Casting and Type Conversion Examples

PowerShell Tips Editor 1 min read
PowerShell Type Casting and Type Conversion Examples

You concatenate two “numbers” and get 510 instead of 15 — because PowerShell read them as strings. PowerShell type casting explicitly controls what data type a value is treated as, preventing the silent bugs that come from PowerShell’s flexible automatic type coercion. This post covers explicit casting, the safe -as operator, and the most common conversions: strings to integers, strings to dates, and objects to Booleans.

Cast with [type] Syntax

Place a type name in square brackets before a value or variable to cast it. If the cast succeeds, you get the value as that type. If it fails, PowerShell throws a terminating error.

# Cast to integer
[int]"42"          # Returns integer 42
[int]3.9           # Returns 3 (truncates — does not round)
[int]"hello"       # ERROR: Cannot convert

# Cast to double
[double]"3.14"     # Returns 3.14

# Cast to string
[string]42         # Returns "42"
[string]$true      # Returns "True"

# Typed variable (locks the type)
[int]$count = 0
$count = "hello"   # ERROR: Cannot convert "hello" to integer

Safe Cast with -as Operator

The -as operator attempts a type conversion and returns $null if it fails — instead of throwing an error. Use it when the value may or may not be convertible and you want to handle both cases gracefully.

# Safe conversion — returns $null on failure
"42"     -as [int]        # Returns 42
"hello"  -as [int]        # Returns $null (no error)
"3.14"   -as [double]     # Returns 3.14

# Use to test whether a value is convertible
$input = "maybe-a-number"
$number = $input -as [int]

if ($null -ne $number) {
    Write-Output "Numeric value: $number"
} else {
    Write-Output "'$input' is not a valid integer"
}

String to Integer and Float

Arithmetic operations on strings concatenate instead of adding. Always cast to a numeric type before arithmetic when your input might be a string.

# Common bug: string concatenation instead of addition
$a = "5"
$b = "10"
$a + $b         # Returns "510" — string concatenation!

# Fix: cast to integer
[int]$a + [int]$b   # Returns 15
$a -as [int] + ($b -as [int])   # Safe version: 15

# Read-Host always returns a string
$userInput = Read-Host "Enter a number"
$value = [int]$userInput
$doubled = $value * 2

String to DateTime

Casting a string to [datetime] uses the current locale to parse the date. For locale-independent parsing, use [datetime]::ParseExact() with an explicit format string.

# Simple cast (locale-dependent)
[datetime]"2026-05-04"       # May 4, 2026
[datetime]"05/04/2026"       # May 4, 2026 (US locale)

# ParseExact — explicit format, locale-independent
$dateStr = "04-May-2026 08:22:11"
$date = [datetime]::ParseExact($dateStr, "dd-MMM-yyyy HH:mm:ss",
    [System.Globalization.CultureInfo]::InvariantCulture)

Write-Output "Year: $($date.Year), Month: $($date.Month), Day: $($date.Day)"
Year: 2026, Month: 5, Day: 4

Object to Boolean

PowerShell has automatic Boolean coercion rules, but explicit [bool] casting makes intent clear. Most values are truthy except: $null, 0, empty string "", and empty array @().

# Automatic truthy/falsy — these are all $false when cast
[bool]$null        # False
[bool]0            # False
[bool]""           # False
[bool]@()          # False

# These are $true
[bool]"hello"      # True
[bool]1            # True
[bool]"0"          # True (non-empty string, even if "0")
[bool]@("item")    # True

Note: [bool]"0" is $true — any non-empty string is truthy, including the string "0" and the string "False".

Parse and TryParse Methods

For robust parsing with error control, use .NET’s TryParse static methods. They return $true on success and populate an output variable — no exceptions thrown.

# Int TryParse
$intResult = 0
if ([int]::TryParse("42", [ref]$intResult)) {
    Write-Output "Parsed integer: $intResult"
} else {
    Write-Output "Not a valid integer"
}

# Double TryParse
$doubleResult = 0.0
[double]::TryParse("3.14", [ref]$doubleResult) | Out-Null
Write-Output "Double value: $doubleResult"

# DateTime TryParse
$dateResult = [datetime]::MinValue
if ([datetime]::TryParse("2026-05-04", [ref]$dateResult)) {
    Write-Output "Parsed date: $($dateResult.ToString('MMMM d, yyyy'))"
}

Common Errors and Fixes

  • Invalid cast throws terminating error — use -as which returns null: [int]"hello" throws a terminating error that stops script execution unless wrapped in try/catch. The -as operator is safer for values from external sources (user input, CSV data, API responses) where the type may be unpredictable. Use -as and then check for $null to validate before proceeding.
  • DateTime parsing is locale-dependent: [datetime]"05/04/2026" means May 4 in the US locale but April 5 in European locales. For any script that processes dates from external files or users in different regions, use [datetime]::ParseExact() with an explicit format and InvariantCulture to guarantee consistent behavior regardless of the machine’s locale settings.

Related Cmdlets / See Also

Wrapping Up

Explicit type casting is a defensive habit that prevents an entire class of hard-to-diagnose bugs in PowerShell. Use [type] casting when you know the input is valid, -as when it might not be, and TryParse when you need both the result and the success flag. As a next step, add type declarations to your function parameters — param([int]$Count, [string]$Name) — to have PowerShell enforce types automatically at the call site.

Send-Item -To