Powershell remove empty spaces from a text file to make it more clear, it avoids unwanted results with Powershell execution, here are the simple steps this article explains.
Windows administrators as part of their routine daily tasks they deal with many servers and also perform the import and export operations with text files, when we are using a text file in the Powershell script for storing the computer names or any other objects and have many empty spaces and line 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