如何使用PowerShell替换多个字符串

时间:2018-02-06 06:09:02

标签: powershell

我想用另外4个字符串替换4个字符串并将它们写入文件。

$file = 'C:\Defender.psd1'
(Get-Content $file) | ForEach-Object {
    $_.replace("'MSFT_MpSignature.cdxml',", "'MSFT_MpSignature.cdxml')")
    $_.replace("'MSFT_MpWDOScan.cdxml')", "")
    $_.replace("'Remove-MpThreat',", "'Remove-MpThreat')")
    $_.replace("'Start-MpWDOScan')", "") `
} | Out-File $file

但不是这样,文件中的每个字符串都被复制了4次。脚本将用于PowerShell 4和5.1。

2 个答案:

答案 0 :(得分:2)

这是因为您将当前的foreach对象放入管道中四次。而是做一次并多次调用替换:

$file = 'C:\Defender.psd1'
(Get-Content $file) | ForEach-Object {
    $_.replace("'MSFT_MpSignature.cdxml',", "'MSFT_MpSignature.cdxml')").replace("'MSFT_MpWDOScan.cdxml')", "").replace("'Remove-MpThreat',", "'Remove-MpThreat')").replace("'Start-MpWDOScan')", "") `
} | Out-File $file

这是一个更易阅读的版本:

$file = 'C:\Defender.psd1'

(Get-Content $file) | ForEach-Object {
    $_.replace("'MSFT_MpSignature.cdxml',", "'MSFT_MpSignature.cdxml')").
    replace("'MSFT_MpWDOScan.cdxml')", "").
    replace("'Remove-MpThreat',", "'Remove-MpThreat')").
    replace("'Start-MpWDOScan')", "") 
} | Out-File $file

答案 1 :(得分:1)

感谢@Martin Brandl的回答,它工作得很好,除了我遇到了CI / CD方面的问题。我的管道对文件编码敏感。原始文件为 UTF-8,但“文件外”将其更改为“ UCS-2 BOM”

因此,我不得不替换保存为原始编码的文件“ Set-Content -Path $ file”

完整示例如下:

$file = 'C:\Defender.psd1'
(Get-Content $file) | ForEach-Object {
    $_.replace("'MSFT_MpSignature.cdxml',", "'MSFT_MpSignature.cdxml')").replace("'MSFT_MpWDOScan.cdxml')", "").replace("'Remove-MpThreat',", "'Remove-MpThreat')").replace("'Start-MpWDOScan')", "") `
} | Set-Content -Path $file