Home » How to Remove Blank Lines From File in PowerShell

How to Remove Blank Lines From File in PowerShell

To remove blank lines from a text file in PowerShell, you can use the Get-Content cmdlet to get the file content and the Where-Object cmdlet to check for empty lines in a file.

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

Method 1: Remove empty lines from a file

Get-Content -Path $filePath | Where-Object {$_.trim() -ne ""}

This example will return the content after removing the blank lines from a text file.

The following example shows how you can use this method.

How to Remove Empty Lines from a File in PowerShell

Suppose that we have a file named “win_log.log” that contains the empty lines in it. In the screenshot, we can see there are multiple blank lines in the file.

The following PowerShell syntax show how to remove blank lines from a text file.

$filePath = "C:\temp\log\win_log.log"
Get-Content -Path $filePath
$dataWithoutEmptyLines = Get-Content -Path $filePath | Where-Object {$_.trim() -ne ""}

Write-Output $dataWithoutEmptyLines

Output:

PowerShell remove blank line from a file
PowerShell remove blank line from a file

In this script, we define a variable $filePath to store the path to the text file.

We then use the Get-Content cmdlet to read the content of a text file “win_log.log” and pipe it to the Where-Object cmdlet.

The Where-Object command checks if the line after trimming whitespace characters from both sides is not an empty string. If the line is empty, it will not be included in the $dataWithoutEmptyLines variable.

Finally, we use the Write-Output cmdlet to print the file content after removing the empty lines from it.

After running the script, it reads the content and finds the empty lines as shown in the screenshot and remove it.

Conclusion

I hope the above article on getting text file content and remove blank lines from text file in PowerShell is helpful to you.

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