To remove empty rows from an array in PowerShell, you can use the Where-Object cmdlet with a condition to check empty or whitespace-only strings and filter them out.
The following method shows how you can do it with syntax.
Method 1: Remove empty rows from the array
$languages = @("Java", "Python","","C#","C++")
$languages | Where-Object {$_.Trim() -ne ""}
This example will filter out empty or whitespace-only strings from an array.
The following example shows how you can use this method to remove blank rows from an array.
Remove Empty Rows From an Array in PowerShell
Suppose you have an array of programming languages stored in $languages variable. To check empty rows from an array in PowerShell, you can use the following script.
# define array with empty and non-empty elements $languages = @("Java", "Python","","C#","C++") # Remove empty elements from array using Where-Object $languages | Where-Object {$_.Trim() -ne ""}
Output:
In this example, we define a $languages variable containing the empty as well as non-empty elements.
We then use the Where-Object cmdlet to iterate over the elements of the $languages array. The Trim() method is called on each element to remove leading and trailing whitespace and then compared to an empty string (“”) using the -ne operator.
After running the PowerShell script, the elements that are not equal to an empty string will be displayed on the console.
Conclusion
I hope the above article on removing the empty rows 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.