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

Null in PowerShell

Nullable variable

The concept “nullable type for value types” in C# is different than how null is handled in PowerShell.

Only reference types can be $null, but PowerShell allows for variables to be any type. If you decide to strongly type a value type, it cannot be $null, but still if you assign $null then PowerShell converts that $null to a default value for many types. For example:

# Altough only reference types can be $null, PowerShell allows $null to be assigned to a value type variable
# The trick here is PowerShell converts that $null to a default value for the corresponding value type (not all value types)
# There are some types that do not have a valid conversion from $null. These types generate a "Cannot convert null to type" error.

PS> [int] $number = $null
PS> $number
0

PS> [bool] $isDone = $null
PS> $isDone
False