One of the most common tasks when writing a script is to check if a variable is NULL or Empty in PowerShell. Null or empty values are always a bit challenging, because what is exactly null?
Checking if a value is null or not has become a lot easier in PowerShell 7 with the Null-coalescing operators. This operator eliminates the need for if-else statements to check if a value is Null or not.
In this article
In this article, I will explain how to check if a value is null, not null, or just empty. We look at the new Null-coalescing operator and why it’s important to start with the $null variable in the comparison.
Simplifying Creation of Empty PowerShell PSCustomObjects using Custom Functions
Creating an empty PSCustomObject in PowerShell is a common task, but the traditional approach can be verbose and repetitive. In this blog post, I’ll walk you through a more structured and efficient way to achieve this using functions and property definitions.
The Traditional Approach
Frequently, developers, including myself, create empty PSCustomObjects like this:
[]{ Name = DisplayName = Telephone = EmailAddress = Gender = Street = City =
}While this method works, it can become unwieldy, especially when dealing with multiple properties. It consumes screen space and lacks a clear structure.
A Structured Solution
To address these concerns, I devised a more organized approach using a custom function New-EmptyCustomObject. This function streamlines the process of creating empty PSCustomObjects and allows for greater flexibility.
{ ( [[]] ) = []{} |
}By utilizing this function, you can now create empty objects in a more organized manner:
= { Users = ( , , , , , , , , , , , , , ) Groups = ( , , , , ) JobRole = ( , , , )
} = .Users = .Groups = .JobRoleWith this approach, you effortlessly generate empty PSCustomObjects while maintaining clear property definitions. This ensures that you can easily manage and track the properties of each PSCustomObject.
Wrapping Up
In conclusion, the streamlined technique I’ve presented enhances the creation of empty PSCustomObjects by utilizing a custom function and well-defined property definitions. This method is not only efficient but also helps maintain a structured and organized codebase.
🤩 Our Amazing Sponsors 👇
I have Excel spreadsheet and few empty blank cells are present in couple of rows. I am writing a powershell script to exclude those empty blank cells while using that spread sheet and display the output as the excluded rows.
Below is the powershell code:
# Load the ImportExcel module
Import-Module ImportExcel
# Set the path to your Excel file
$excelFilePath = "C:\Users\madamaneril\powershell\NSG_Rules.xlsx"
# Read the Excel file
$excelData = Import-Excel -Path $excelFilePath
# Filter rows with empty cells
$nonEmptyRows = $excelData | Where-Object { $_.PSObject.Properties.Value -notcontains ""
}
# Display the rows without empty cells
if ($nonEmptyRows) { $nonEmptyRows | Format-Table
} else { Write-Host "No rows with empty cells found."
}After executing the above script, it is giving the all rows as output not the empty cell rows. I have tried different ways to test the same but not getting the expected output. Can someone please help me if any changes needs to do to exclude the empty blank cells and display the rows as output.
68 gold badges673 silver badges862 bronze badges
Therefore, replace
$_.PSObject.Properties.Value -notcontains ""with$_.PSObject.Properties.Value -notcontains $nullin order to detect rows that do not have empty cells – or use-contains $nullto get those that do have empty cells.Additionally, you need to at least compare the count of filtered rows to the total count of rows in order to detect if rows with empty cells were present.
if ($nonEmptyRows.Count -lt $excelData.Count) { Write-Host 'Rows with empty cells found.' } Write-Host 'All rows with non-empty cells:' $nonEmptyRows | Format-Table- However, you may want to create a list of those partially filled-in rows too.
- The intrinsic
.Where()method offers a convenient way to partition an input list into two lists based on a filter criterion, yielding one list with all elements that do meet the criterion and another with those that do not. See the code below.
$excelFilePath = "C:\Users\madamaneril\powershell\NSG_Rules.xlsx"
# Read the Excel file
[array] $excelData = Import-Excel -Path $excelFilePath
# Partition rows into two lists:
# * One with only rows *without* empty ($null) values.
# * On with rows *with* empty values.
$rowsFullyFilled, $rowsWithEmptyCells = $excelData.Where( { $_.PSObject.Properties.Value -notcontains $null }, 'Split'
)
# For-display output of the results:
Write-Verbose -Verbose 'Rows WITHOUT empty cells:'
$rowsFullyFilled | Format-Table | Out-Host
Write-Verbose -Verbose 'Rows WITH empty cells:'
$rowsWithEmptyCells | Format-Table | Out-Host68 gold badges673 silver badges862 bronze badges
Do you want to check if an array is empty in PowerShell? In this blog post, we’ll explore various methods to check if an array is empty in PowerShell.
To check if an array is empty in PowerShell, you can test if the count of the array is zero by using $array.Count -eq 0. If this condition returns $true, the array is empty; otherwise, it contains one or more elements. You can also use $array -eq $null to check if the array is uninitialized or has been explicitly set to $null.
An array is a data structure that holds multiple values in a single variable. Each item in an array is called an element, and each element is accessible through its index.
Here’s how you can create an array in PowerShell:
$myArray = @(1, 2, 3, 4, 5)This array contains five elements, each with a numerical value.
Now, let us see how to check if the above array is empty in PowerShell.
1. Using the Count Property
One of the simplest ways to check if an array is empty in PowerShell is by using the Count property. This property returns the number of elements in the array.
Here’s how you can use it:
$myArray = @()
if ($myArray.Count -eq 0) { Write-Host "The array is empty."
} else { Write-Host "The array is not empty."
}If the Count property is equal to 0; the PowerShell array is empty.
You can see the output in the screenshot below after I executed the script using Visual Studio code.

2. Using the Length Property
Similar to the Count property, the Length property can also be used to determine if an array is empty in PowerShell. The Length property also returns the number of elements in the array.
Here’s an example using the Length property in the PowerShell array:
$myArray = @()
if ($myArray.Length -eq 0) { Write-Host "The array is empty."
} else { Write-Host "The array is not empty."
}Check out the screenshot below for the output.

3. Using Conditional Statements
PowerShell treats empty arrays as $false when evaluated in a boolean context. This means you can use a simple if statement to check if an array is empty.
Here’s an example:
$myArray = @()
if ($myArray) { Write-Host "The array is not empty."
} else { Write-Host "The array is empty."
}4. Using the Any() Method
For PowerShell versions 4.0 and above, you can use the Any() method to check if an array is not empty. The Any() method is a part of LINQ (Language Integrated Query), and it returns True if the array contains at least one element.
Here’s how to use the Any() method:
$myArray = @()
if ($myArray.Any()) { Write-Host "The array is not empty."
} else { Write-Host "The array is empty."
}However, keep in mind that if you’re working with an array that could potentially contain $null elements, you might want to filter those out first before calling Any().
Understanding Null and Empty Arrays in PowerShell
It’s important to distinguish between a null array and an empty array. A null array is a variable that has not been assigned any value, not even an empty array. An empty array, on the other hand, is an array that has been initialized but contains no elements.
Here’s an example to illustrate the difference:
$nullArray = $null
$emptyArray = @()
Write-Host "Null Array Count: $($nullArray.Count)"
Write-Host "Empty Array Count: $($emptyArray.Count)"In this case, trying to access the Count property on a null array will result in an error because $null does not have a Count property. The empty array will correctly report a count of 0.
Conclusion
In this PowerShell tutorial, I have explained the below methods to check if an array is empty in PowerShell:
- Using the Count Property
- Using the Length Property
- Using Conditional Statements
- Using the Any() Method
You may also like:
Do you need to create an empty array in PowerShell? In this PowerShell tutorial, I will explain how to create an empty array in PowerShell and work with PowerShell empty arrays.
An empty array in PowerShell is essentially a starting point. It’s a container ready to be filled with elements. Creating an empty array is useful when you know you will need to store a collection of items but don’t yet have the items to store at the time of array creation. You can then add elements to the array as they become available.
Create an Empty Array in PowerShell
$myArray = @()This command initializes $myArray as an empty array. At this point, $myArray contains no elements.
Adding Elements to an Empty Array
Once you have an empty array, you might want to add elements to it. Although PowerShell arrays are fixed in size once created, you can still simulate adding elements by creating a new array that includes the elements of the existing array plus the new element. Here’s an example:
$myArray += "new element"This line takes the current $myArray, adds a new element to it, and then assigns the result back to $myArray. Keep in mind that this process is not the most efficient for adding many elements because it creates a new array with each addition.
You can look at the screenshot below, I have created an empty array in PowerShell using VS code.

Check out PowerShell Append to Array
Alternative Methods to Create an Empty Array
$myArray = [array]@()This method makes it explicitly clear that $myArray is intended to be an array data type.
Create an empty array with properties in PowerShell
Creating an empty array with properties in PowerShell involves defining an object with the desired properties and then storing these objects in an array. This is often done using custom objects. Here’s an example:
First, define a custom object with the properties you want. For instance:
$customObject = New-Object PSObject -Property @{ Property1 = $null Property2 = $null
}In this example, Property1 and Property2 are the names of the properties, and they are initially set to $null.
Next, create an empty array to store such objects:
$myArray = @()Now, you can add the custom object to the array:
$myArray += $customObjectThis array, $myArray, now contains one item, which is a custom object with Property1 and Property2. You can add more objects with the same properties to the array using the same method. Each object can have its properties set to different values as needed.
Create an empty string array in PowerShell
Here’s an example of how you can create an empty array of strings in PowerShell:
$stringArray = @()This command initializes $stringArray with an empty array. You can then add strings to this array using various methods, such as the += operator to append an element:
$stringArray += "First string"
$stringArray += "Second string"After these operations, $stringArray will contain two elements: “First string” and “Second string”.
PowerShell: create an empty array with headers
In PowerShell, an “array with headers” typically refers to a collection of objects with named properties, rather than a traditional array. To create such a collection, you can use a PSCustomObject or a hashtable, and then store these objects in an array.
Here’s an example of how to create an empty array that will hold objects with headers (named properties):
# Define an empty array to hold the custom objects
$objectArray = @()
# Define a new object with named properties (headers)
$object = New-Object PSObject -Property @{ Header1 = $null Header2 = $null Header3 = $null
}
# Add the object to the array
$objectArray += $objectIn this example, $objectArray is an array that is intended to hold objects with three properties: Header1, Header2, and Header3. Initially, the array contains one object with all properties set to $null.
Create an empty array of size in PowerShell
In PowerShell, you can create an array with a predefined size, but it’s important to note that arrays in PowerShell are fixed in size once they are created. To create an array with a specific size, you typically initialize the array with a certain number of elements. However, since PowerShell arrays are not like traditional statically-sized arrays found in languages like C#, the approach is a bit different.
# Create an array with 10 elements, all initialized to $null
$arrayOfSize = New-Object object[] 10In this example, $arrayOfSize is an array that has 10 elements, each initialized to $null. You can then assign values to each element of the array by accessing them using their index.
Here’s how you can assign a value to the first element (index 0) of the array:
$arrayOfSize[0] = "First element"If you want to create an array that is initialized with a default value other than $null, you can use a loop to populate the array. For instance, to create an array of 10 empty strings:
# Create an array of 10 empty strings
$arrayOfSize = 1..10 | ForEach-Object { "" }This uses a ForEach-Object loop to set each of the 10 elements to an empty string ("").
Conclusion
In this PowerShell tutorial, I have explained how to create an empty array in PowerShell using various methods.
You may also like:
What is Null
When we are talking about NULL in a programming or scripting language, then we can assume it’s a variable that doesn’t have any value. In PowerShell however, Null can either be an empty value or an unknown value.
The NULL value is written as $null in PowerShell, and it’s one of the automatic variables. It’s an object with the value NULL. This allows you to use $null as a placeholder in collections or assign it to a variable.
A good way to demonstrate this is to create a collection and count the length of it. As you can see in the example below, the $null object is counted as one of the objects in the collection:
$fruits = "Apple", $null, "Pear" $fruits.count 3
NULL vs Empty
Besides $null values, we can also have empty values in PowerShell. The difference between the two is that an empty value is a variable that is declared and assigned an actual empty value.
If we look at the example below, then the first variable is $null, even though we haven’t assigned the NULL variable to it. The other variables are not null but are empty.
# Null variable $variableIsNull # Empty string variable $emptyString = "" # Empty array variable $emptyArray = @()
There are a couple of ways to check if a variable or result is Null in PowerShell. The recommended way to check if a value is NULL is by comparing $null with the value:
if ($null -eq $value) { Write-Host 'Variable is null';
}Important to note that the method above, returns to true on two occasions. When the value is NULL, as you would expect, but also when the variable is not defined.
When you want to check if a value is Not Null, then you can use the comparison operator -ne instead:
if ($null -ne $value) { Write-Host 'Variable is not null';
}- not Null
- not empty
- not 0
- not an array,
- Length is not equal to 0
- not $false
if ($value) { Write-Host 'Variable is not null or empty';
}Null on the left-hand side
When you are using Visual Studio code or another IDE to write your PowerShell scripts, you will get a warning when you place the $null variable on the right-hand side in a comparison. This is for a good reason.
In some cases, placing them $null on the right-hand side can result in unexpected results. Take for example the array below. If we place $null on the left side, it will check if $null is not equal to our $array, which it isn’t, so it returns true.
# Array $a = 1, 2, $null, 4, $null, 6 # Check if the Array is not empty (null) $null -ne $a # returns true # Return everything from the array that is not Null $a -ne $null # Returns 1 2 4 6
But when you place $null it on the right-hand side, then it will return everything from the array, that does not equal $null.
Null-coalescing Operator
If you are using PowerShell 7, and you actually should, then you can use one of the new null conditional operators to quickly check if a variable or property is null or not. This way you don’t need to write If statements every time you only want to check if a variable is null or not.
The Null coalescing operator ?? returns the value on the left side if it’s not null. If the value on the left is null, then it returns the results on the right side.
$nullableVariable = $null # If $nullableVariable equal NULL, return "Default Value" $defaultValue = $nullableVariable ?? "Default Value" # Result of $defaultValue The value is: Default Value
We can also use this method to check the result of a function and call another function or cmdlet if the results are null:
function Get-LastUsedDate { return $null
}
# Use null-coalescing operator to handle null return value
$result = (Get-LastUsedDate) ?? (Get-Date).ToShortDateString()It’s also possible to chain multiple Null Coalescing operators together to find or return the first variable that is not null.
# Define a chain of variables where one may be null $firstVariable = $null $secondVariable = "Value 2" # Use null-coalescing operator to choose the first non-null value $chosenValue = $firstVariable ?? $secondVariable ?? "No value found" # Output the chosen value Write-Host "Chosen value: $chosenValue"
Null-coalescing Assignment Operator
The Null-coalescing assignment operator ??= makes it easier to check if a variable on the left-hand side of the operator is null or not, and assign the value of the right-hand side to it if it’s null.
In the example below, we check if the variable $existingValue is null or not. If it’s null, then we set the variable to the default value:
# Variable that may or may not have a value $existingValue = "Existing Value" # Assign a new value using the Null-coalescing assignment operator $existingValue ??= "Default Value" # Result of $existingValue Existing Value
Null-conditional operators ?. and ?[]
If you access a property or element without the null-conditional operator, you normally won’t get an error. Only if you are using Strict mode you do get an error. So in these cases, it’s important to check if you are not trying to access a member of a null-valued object.
# Empty object
$cities = $null
# Set strictmode for test
Set-StrictMode -Version 2
# Will throw an error
$cities.language
# No error with null-conditional operator
${cities}?.languageCheck for Null in a Function
When you are creating your own functions in PowerShell, you can ensure that a parameter is not null or empty by using the validator ValidateNotNullOrEmpty. This way you don’t have to do additional checks in the function.
function Test-Input { param( [Parameter(Mandatory)] [ValidateNotNullOrEmpty()] [string]$input ) Write-Host "Input received: $input"
}
# Test the function
Test-Input -input "Hello"Check if Empty in PowerShell
Besides checking if a value is Null another common practice is to check if a value is empty. You can only check if a string or array is empty in PowerShell.
To check if a string is empty, simply compare it with ""
$string = ""
if ($string -eq "") { write-host "Empty string found"
}If you want to check if an array is empty, the best option is to check the length of the array:
$array = @()
if ($array.Count -gt 0) { write-host "Array is not empty"
}IsNullOrEmpty
When working with strings, you can also use the static string function to check if the value is either null or empty. If you want to know if the value is not null or empty, then you only need to place -not in front of it
$string = $null
if ([String]::IsNullOrEmpty($string)) { write-host "Empty string"
}
# Check if not empty or null
if (-not [String]::IsNullOrEmpty($string)) { write-host "Striong is Not empty"
}Wrapping Up
Checking for Null values makes your script more robust and will result in fewer errors in your script. Make sure that you try out the new PowerShell null-coalescing operators because they are quite handy to work with.
Also, make sure that you always keep the $null values on the left-hand side of the comparison.
I hope you liked this article, if you have any questions, just drop a comment below!

