如何使用 PowerShell 在文本文件中查找和替换单词?

powershellmicrosoft technologiessoftware & coding更新于 2026/2/12 3:37:17

要在 PowerShell 中搜索单词并在文件中进行替换,我们将使用字符串操作。事实上,PowerShell 中的 Get-Content 命令几乎可以读取任何类型的文件内容。在本文中,我们将以如下所示的文本文件为例。

Get-Content C:\Temp\TestFile.txt

输出

PS C:\> Get-Content C:\Temp\TestFile.txt
# In case of linux, networkInterface names are of the form eth*
# In Windows, please use the network full name from Device Manager
networkInterfaces: ["Microsoft Hyper-V Network Adapter"
]

overrideMetricsUsingScriptFile: false

scriptTimeoutInSec: 60

scriptFiles:
- osType: windows
filePath: monitors/NetworkMonitor/scripts/windows-metrics.bat
- osType: unixBase
filePath: monitors/NetworkMonitor/scripts/unix-base-metrics.sh

以上输出是文件的内容,我们将对其进行处理。我们需要找到 NetWorkMonitor 一词并将其替换为"Active"。请注意,以上文件是文本文件,因此我们不需要将其转换为字符串,但如果有其他扩展名,则可能需要在执行任何操作之前使用 .ToString() 命令或 Out-String 方法将输出转换为字符串。

现在,我们首先找到请求的字符串,然后使用 Select-String cmdlet 检查需要替换多少行。

(Get-Content C:\Temp\TestFile.txt) | Select-String -Pattern "NetworkMonitor"

输出

PS C:\> (Get-Content C:\Temp\TestFile.txt) | Select-String -Pattern "NetworkMonitor"
   filePath: monitors/NetworkMonitor/scripts/windows-metrics.bat
   filePath: monitors/NetworkMonitor/scripts/unix-base-metrics.sh

我们发现有两行包含"NetworkMonitor"一词。我们需要用以下命令替换该词。您还可以将 Get-Content 的输出存储在变量中并对其进行操作。

(Get-Content C:\Temp\TestFile.txt) -replace "NetworkMonitor","Active"

输出

PS C:\> (Get-Content C:\Temp\TestFile.txt) -replace "NetworkMonitor","Active"
# In case of linux, networkInterface names are of the form eth*
# In Windows, please use the network full name from Device Manager
networkInterfaces: ["Microsoft Hyper-V Network Adapter"
]

overrideMetricsUsingScriptFile: false

scriptTimeoutInSec: 60

scriptFiles:
- osType: windows
filePath: monitors/Active/scripts/windows-metrics.bat
- osType: unixBase
filePath: monitors/Active/scripts/unix-base-metrics.sh

上述命令替换了文件内容,但尚未存储,因此为了保存更新后的文件,我们将使用 Set-Content 命令,最终代码如下:

(Get-Content C:\Temp\TestFile.txt) -replace "NetworkMonitor","Active" | Set-Content
C:\Temp\Testfile.txt -Verbos

您也可以选择其他路径来保存文件。如果文件是只读的,请在 Set-Content 命令中使用 -Force 参数。


相关文章