Home ยป Remove Null Values From PowerShell Array

Remove Null Values From PowerShell Array

To remove null values from an array in PowerShell, you can use the Where-Object cmdlet with a condition to check null values and filter out.

The following method shows how you can do it with syntax.

Method 1: Remove null values from the array

$languages  = @("Java", "Python",$null,"C#","C++",$null)
$languages | Where-Object {$_ -ne $null}

This example will filter out null values from an array.

The following example shows how you can use this method to remove null values from an array in PowerShell.

Remove Null Values From the Array in PowerShell

Suppose you have an array of programming languages stored in $languages variable. Use the following script to remove the null values from an array in PowerShell.

# define array with null and non-null elements
$languages  = @("Java", "Python","","C#","C++")

# remove null elements from array using Where-Object
$languages | Where-Object {$_ -ne $null}

Output:

PowerShell remove null values from array
PowerShell remove null values from array

In this example, we define a $languages variable containing the null as well as non-null elements.

We then use the Where-Object cmdlet to iterate over the elements of the $languages array, compare each element with the $null condition, and filter out the null values using the condition $_ -ne $null

After running the PowerShell script, null elements will be removed from the array.

Conclusion

I hope the above article on removing the null values from an array using PowerShell is helpful to you.

You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.