Powershell removes empty lines from a text file if there are empty lines in a file that can cause unwanted results when you execute a script, here is the simple Powershell code to clear the empty lines in PowerShell.
Windows administrators deal with many servers every day and also perform the import and export operations with text files, when you are using a text file in Powershell script for storing the computer names or any other objects and have many empty lines then script fails to execute. The below shortcode of the script removes the empty lines and white spaces in the text file.
#Your text file location $file = "C:\Users\Raj\Desktop\serverlist2.txt" (gc -Path $file) | ? {$_.trim() -ne " " } | set-content -Path $file (gc -Path $file) | ForEach {$_.TrimEnd()} | ? {$_.trim() -ne '' } $file = Get-Content -Path "C:\Users\Raj\Desktop\serverlist2.txt" $file | ForEach {$_.TrimEnd()} | ? {$_.trim()
The output of the script with screenshots.
Before the script execution, the file is having many empty spaces and empty lines, see the screenshot below.
After the script execution, the empty spaces and empty lines have been removed, see the screenshot below.
Thank you for reading this article, if you have any questions please let us know.
Thank you for visiting my site, for any scripts in these articles you are testing please make sure you have tested this script in our lower environment before you run in production.
Leave a Reply Cancel reply