How to remove empty string/lines from PowerShell?


In many instances, you need to remove empty lines or strings from the PowerShell string array or the files. In this article instead of removing empty string, we will get the result or filter the output from lines that are not empty. In this way, we can get the output without empty lines.

Consider the example below, we have a file called EmptryString.txt and we need to remove empty lines from the content.

The content of the text file is as below.

PS C:\Windows\System32> Get-Content D:\Temp\EmptyString.txt
This is example of empty string
PowerShell
PowerShell DSC
String Array
Hello

You just need to apply the condition where the line is not empty. See the code below.

Example

Get-Content D:\Temp\EmptyString.txt | where{$_ -ne ""}

Output

This is example of empty string
PowerShell
PowerShell DSC
String Array
Hello

Similarly, you can use the above command to remove empty lines from the string array. For example,

$str = "Dog","","Cat","","Camel","","Tiger"
$str
PS C:\Windows\System32>
$str
Cat
Camel
TigerDog

Now apply the same logic to remove the empty lines.

Example

$str | where{$_ -ne ""}

Output

PS C:\Windows\System32> $str | where{$_ ne ""}
Dog
Cat
Camel
Tiger

Updated on: 15-May-2020

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements