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

标签 powershell powershell-2.0

我是 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

提前谢谢您。我感谢任何帮助。

最佳答案

您可以通过简单的正则表达式使用-replace命令:

-replace '\s'

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

试试这个:

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

关于PowerShell - 删除txt文件中单词之间的空格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36934576/

相关文章:

powershell - 安装时编辑 Chocolatey 源

xml - 确定 XML 节点存在

powershell - 将相对路径转换为绝对字符串路径

powershell - 有没有办法在powershell中使用WebClient对象来监控下载进度?

powershell - 如何抑制用户在没有参数参数的情况下调用我的 powershell 脚本时发生的错误

powershell - PowerShell 中 [Char[]] 的用途

powershell - 如何使用Powershell替换文件的一部分?

Powershell:压缩文件

Powershell 前景色

powershell - PowerShell 中是否有字符串连接快捷方式?