Author : MD TAREQ HASSAN | Updated : 2023/03/18

Type conversion

A type conversion is performed when a value of one type is used in a context that requires a different type.

In PowerShell everything is an object, that includes the cmdlets. Casting is the process of converting one object type into another.

See: Type conversion details

Implicit casting

In implicit casting, one type of data is converted or casted to another type automatically without causing any value/precision loss.

[int] $intVal = 10.4;
Write-Host (10.7).GetType() # System.Double
Write-Host $intVal.GetType() # System.Int32
Write-Host $intVal # 10 (implicitly casted)

[double] $doubleVal = $intVal + 0.5
Write-Host $intVal.GetType() # System.Int32
Write-Host $doubleVal.GetType() # System.Double
Write-Host $doubleVal # 10.5, $intVal was implicitly casted to double before performing operation

# 
# string to numbger
#
[int] $intValStr = "13"
Write-Host $intValStr.GetType() # System.Int32
Write-Host $intValStr # 13

[double] $doubleVal = "11.527"
Write-Host $doubleVal.GetType() # System.Double
Write-Host $doubleVal # 11.527

#
# number to string
#
[int] $intVal = 15
[double] $doubleVal = 12.85

[string] $strInt = $intVal
Write-Host $strInt.GetType() # System.String
Write-Host $strInt # "15"

[string] $strDouble = $doubleVal
Write-Host $strDouble.GetType() # System.String
Write-Host $strDouble # "12.85"

Explicit casting

Explicit casting means converting one type of data to another manually (intentionally/forcefully).

[double] $doubleVal = 15.458796
$result = [int]$doubleVal # explicit casting
Write-Host $result.GetType() # System.Int32
Write-Host $result # 15

[string] $doubleValStr = "14.854"
# [double] $result = ($doubleValStr + 0.756) # => ERROR
[double] $result = ([double]$doubleValStr + 0.756) # => OK
Write-Host $result.GetType() # System.Double
Write-Host $result # 15.61

Type casting operator

Syntax:

<input> <operator> [.NET type]

Example:

"str" -is [string]            # True

(get-date) -is [DateTime]     # True

(get-date) -isnot [DateTime]  # False

"5/7/07" -as [DateTime]       # Monday, May 7, 2007 12:00:00 AM