farag
farag

Reputation: 375

How to replace multiple strings using PowerShell

I want to replace 4 strings with 4 another ones and write them to 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

But instead of this every string in the file has been duplicated 4 times. Script will be used for PowerShell 4 and 5.1.

Upvotes: 4

Views: 11550

Answers (2)

Major
Major

Reputation: 6658

Thanks @Martin Brandl for the answer it was working perfectly except I run into some issues with CI/CD. My pipeline is sensitive to file Encoding. The original file was UTF-8 but "Out-File" changed it to "UCS-2 BOM".

So I had to replace the files save code ot "Set-Content -Path $file" it preserves to original encoding.

Here is the full example:

$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

Upvotes: 2

Martin Brandl
Martin Brandl

Reputation: 58931

Thats because you are putting the current foreach object into the pipeline four times. Instead do it one time and call the replace multiple times:

$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

Here a more readable version:

$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

Upvotes: 5

Related Questions