How to Check if Array is Empty in PowerShell (With Examples)


Often you may want to check if an array is empty in PowerShell.

You can use the following methods to do so:

Method 1: Check if Array is Empty (Return True or False)

$my_array.count -eq 0

This particular example checks if the array named $my_array is empty and returns either True or False as a result.

Method 2: Check if Array is Empty (Return String as Output)

if ($my_array.count -eq 0) {
    Write-Host "The array is empty"
} else {
    Write-Host "The array is not empty"
}

This particular example checks if the array named $my_array is empty and then uses Write-Host to output a string with custom text as a result.

The following examples shows how to use each method in practice.

Example 1: Check if Array is Empty (Return True or False)

We can use the following syntax to create an array named $my_array with no values and then check if the array is empty:

$my_array = @()
$my_array.count -eq 0

The following screenshot shows how to use this syntax in practice:

This returns True, which tells us that the array named $my_array is indeed empty.

Example 2: Check if Array is Empty (Return String as Output)

We can use the following syntax to create an array named $my_array with no values and then use an if else statement to check if the array is empty, returning custom text as a result:

$my_array = @()

if ($my_array.count -eq 0) {
    Write-Host "The array is empty"
} else {
    Write-Host "The array is not empty"
}

The following screenshot shows how to use this syntax in practice:

PowerShell check if array is empty in if else statement

This returns “The array is empty” because the array named $my_array is indeed empty.

Feel free to replace this text with whatever output you would like to display with the Write-Host cmdlet.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Check if String is Empty
PowerShell: How to Check if File is Empty
PowerShell: How to Check if Folder Exists

Leave a Reply