Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell - Remove spaces between words from txt file

I am a noob at powershell and still trying to learn scripting but stumbling on the basics. I have a text file that contains a list of websites

Default Websites
Power Shell
Hello World

I need to remove the white spaces between the words so I get the outcome below

DefaultWebsites
PowerShell
HelloWorld

I have tried using the Trim('') command but it is not removing the white spaces.

Here is my original script that removes all white spaces at the beginning and the end and any blank lines. what do I need to add to the script to remove the white spaces in between words?

Get-WmiObject -Class IIsWebServerSetting -Namespace "root\microsoftiisv2" | Select ServerComment | Format-Table -HideTableHeaders | out-file c:\website.txt
$b = Get-Content -Path C:\website.txt
$b | ForEach {$_.TrimEnd()} | ? {$_.trim() -ne '' } > C:\website.txt

Thank you in advance. I appreciate any help.

like image 725
Deano Avatar asked Mar 13 '23 11:03

Deano


2 Answers

You can use the -replace command with a simple regex:

-replace '\s'

\s match any white space character [\r\n\t\f ]

Try this:

[System.IO.File]::WriteAllText(
        'C:\website.txt',
        ([System.IO.File]::ReadAllText('C:\website.txt') -replace '\s')
    )
like image 130
Martin Brandl Avatar answered Mar 28 '23 07:03

Martin Brandl


I would go with this approach (where the hero is Replace function):

Get-WmiObject -Class IIsWebServerSetting -Namespace "root\microsoftiisv2" | Select ServerComment | Format-Table -HideTableHeaders | out-file c:\website.txt
$b = Get-Content -Path C:\website.txt
@(ForEach ($a in $b) {$a.Replace(' ', '')}) > C:\Website2.txt
like image 37
Eduard Uta Avatar answered Mar 28 '23 09:03

Eduard Uta