PowerShell - 从txt文件中删除单词间的空格

4

我对Powershell还是个新手,在学习脚本方面遇到了基础问题。我有一个包含网站列表的文本文件。

Default Websites
Power Shell
Hello World

我需要删除单词之间的空格,以便得到以下结果。
DefaultWebsites
PowerShell
HelloWorld

我尝试使用Trim('')命令,但它没有删除空格。

这是我的原始脚本,可以删除开头和结尾以及任何空行中的所有空格。我需要在脚本中添加什么来删除单词之间的空格?

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

提前感谢您,我非常感激任何帮助。

2个回答

4
您可以使用简单的正则表达式和-replace命令:
-replace '\s'

\s 匹配任何空白字符 [\r\n\t\f ]

尝试这样:

[System.IO.File]::WriteAllText(
        'C:\website.txt',
        ([System.IO.File]::ReadAllText('C:\website.txt') -replace '\s')
    )

谢谢您的回复,但是Eduard Uta的解决方案更简单,对于我的脚本来说更好,因为它只是一个较大脚本的一小部分。 - Deano

3
我会采用这种方法(英雄是替换函数):
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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接