Author : MD TAREQ HASSAN | Updated : 2023/03/18
Null in PowerShell
null
is an automatic variable in PowerShell used to represent NULL- PowerShell treats
$null
as an object with a value of NULL - Anytime you try to use a variable that you have not initialized, the value is
$null
(this is one of the most common ways that$null
sneaks into code) - If you mistype a variable name, then PowerShell sees it as a different variable and the value is
$null
- Value coming from a command that don’t give any results will be
$null
- If you have a collection but try to access an element that is not in the collection, you get a
$null
result - If you try to access a property or sub property of an object that doesn’t have the specified property, you get a $null (It doesn’t matter if the variable is
$null
or an actual object) - Calling a method on a $null object throws a RuntimeException
$null
should be on the left side of equality comparisons (use PSScriptAnalyzer to check:Invoke-ScriptAnalyzer .\program.ps1
)$null.Count => 0
foreach
loop doesn’t enumerate over a$null
collection- More: https://learn.microsoft.com/en-us/powershell/scripting/learn/deep-dives/everything-about-null
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