Table of Contents
1. Introduction
In PowerShell, checking if a variable is null (or in PowerShell terms, $null) is a fundamental task in scripting, especially when dealing with the output of commands, function returns, or processing user input.
For instance, a variable storing data from database might be null if no data is present.
In this article, we will see different ways to check if variable is Null in PowerShell.
2. What is null in PowerShell?
null
refers to variable that has no value assigned to it and is represented by $null
in PowerShell. It is generally used to portray absence of a value or non-existent state.
In Powershell, $null
is treated as an object with a value of null
. It is singleton object, meaning there is only one instance of $null
in PowerShell environment.
3. Using the Equality Operator -eq
The eq
operator is the most straightforward and recommended method to check if a variable is null.
1 2 3 4 5 6 7 8 9 |
$myVariable = $null if ($myVariable -eq $null) { Write-Host "Variable is null." } else{ Write-Host "Variable is not null." } |
1 2 3 |
Variable is null. |
Here, the expression $myVariable -eq $null
checks if myVariable
is null. If true, it prints Variable is null
;otherwise, it prints Variable is not null
.
This method is fast and efficient, as it does basic comparison operation.
3.1 Handling Result from Database Call
If we are doing null check for result from database query, it might return [DBNULL]
which is different than $null
.
Let’s write a custom function to check if variable is $null
or DBNULL
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function IsNullOrDbNull { param ( [Parameter(Mandatory=$true)] $Value ) return $Value -eq $null -or [System.DBNull]::Value.Equals($Value) } # Example usage: $myVar = $null # This could be $null or a result from a database query if (IsNullOrDbNull -Value $myVar) { Write-Host "Variable is null or DB null" } else { Write-Host "Variable has a value" } |
Explanation:
- The function
IsNullOrDbNull
takes a mandatory parameter$Value
. - It checks if
$Value
is null using-eq
operator or if it is equal to DBNULL using[System.DBNull]::Value.Equals($Value)
. $myVar = $null
is used to assign$null
to$myVar
.$myVar
can have result from database query as well.IsNullOrDbNull
returns true in case$Value
is either$null
orDBNULL
.- The expression
if (IsNullOrDbNull -Value $myVar)
calls functionIsNullOrDbNull
with Parameter$myVar
and checks if it returns true.
4. Using Conditional Statement
Conditional statement can be used to check if variable is null, especially when working with multiple conditions.
1 2 3 4 5 6 7 8 |
$myVariable = $null if ($myVariable) { Write-Host "Variable has a value" } elseif ($myVariable -eq $null) { Write-Host "Variable is null" } |
Here, if
block checks if variable has a truthy value, so it will go to elseif
block even if value is 0
, $false
, an empty String, an empty array, and not just $null
, and that’s the reason, we have put explicit check in elseif
statement if variable is $null
.
5. Using Null-Coalescing Operators [ Supported in PowerShell 7.0 versions]
??
is the null-coalescing operator. It returns the left-hand operand if it’s not $null
, otherwise the right-hand operand. It is generally useful when we want to assign default value to variable when it is $null
.
Let’s see with the help of example:
1 2 3 4 5 |
$myVar = $null $result = $myVar ?? "default value" Write-Host $result # Outputs 'default value' |
Let’s assign some value to $myVar
and check the output.
1 2 3 4 5 |
$myVar = "Java2blog" $result = $myVar ?? "default value" Write-Host $result # Outputs 'Java2blog' |
6. Checking for null for String Variables
For string values, we can use two more methods i.e. IsNullorEmpty()
and IsNullOrWhiteSpace()
to check if variable is null.
Let’s go through each of them:
6.1 Using IsNullorEmpty()
IsNullorEmpty()
checks if a string variable is either null or empty. It is efficient and more comprehensive for basic string checks.
Let’s see with the help of example:
1 2 3 |
[string]::IsNullOrEmpty($newVariable) |
1 2 3 |
True |
In the above code, IsNullOrEmpty()
method is used to determine whether the string variable named $newVariable
is null
or not, and we got True
, which means the specified variable is null
. Now, execute the following code to assess whether the given variable is empty.
1 2 3 4 |
$newVariable='' [string]::IsNullOrEmpty($newVariable) |
1 2 3 |
True |
The above code fence also returned True
, meaning $newVariable
is empty; otherwise, we would get False
. So, let’s assign a value to $newVariable
as given below and observe the output.
1 2 3 4 |
$newVariable = 'Hello World' [string]::IsNullOrEmpty($newVariable) |
1 2 3 |
False |
This time, we got False
because the $newVariable
is not null
or empty but contains a string type value, Hello World
.
6.2 Using IsNullOrWhiteSpace()
Method
we can use the IsNullOrWhiteSpace()
method to check if the specified string variable is null
, empty, or contains whitespace characters only.
1 2 3 |
[string]::IsNullOrWhiteSpace($Variable) |
1 2 3 |
True |
This approach is similar to the previous one, where we used the IsNullorEmpty()
method, except for one difference, it not only tells that the specified variable is null
or empty but informs if the given variable contains whitespace characters only.
The IsNullOrWhiteSpace()
method returns True
if the given variable is null
, empty, or contains a whitespace
character; otherwise, False
. Here, null
means the $Variable
is not yet assigned any value, empty means set with an empty string, and the third scenario holds whitespace characters only.
Let’s see another example to understand all of these situations.
1 2 3 4 5 6 7 8 9 10 11 12 |
[string]::IsNullOrWhiteSpace($Variable) $Variable='' [string]::IsNullOrWhiteSpace($Variable) $Variable=' ' [string]::IsNullOrWhiteSpace($Variable) $Variable='How are you?' [string]::IsNullOrWhiteSpace($Variable) |
1 2 3 4 5 6 |
True True True False |
First, we got three True
values because $Variable
was not initialized at the beginning, then assigned with an empty string and third, held whitespace characters only. Lastly, we received only one False
because How are you?
was assigned to $Variable
.
Note: This method only applies in PowerShell versions 3.0 and above.
7. Handling $null in Collections
When dealing with collections like arrays or lists, checking for $null items requires iterating through the collection.
1 2 3 4 5 6 7 8 9 10 |
$myArray = @(1, $null, 3) $nullItem = $myArray -contains $null if ($nullItem) { Write-Host "Array contains null value" } else { Write-Host "Array does not contain null value" } |
1 2 3 |
Array contains null value |
-Contains
operator checks if array contains element.
Above code checks if array contains any $null
value. In our example, $myArray
contains $null
value, hence output is Array contains null value
.
8. Conclusion
In this article, we have discussed ways to check if variable is null in PowerShell.
The equality operator (-eq
) provides a straightforward check, while conditional statements offer more flexibility for complex scenarios.
The null-coalescing operator (??)
is a modern and efficient way to handle $null values, especially when assigning default values.
The IsNullorEmpty()
and IsNullOrWhiteSpace()
methods are particularly useful for string variables, offering a more comprehensive check.