Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace multiple strings using PowerShell

Tags:

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.

like image 687
Sanctuary Avatar asked Oct 23 '25 16:10

Sanctuary


2 Answers

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
like image 108
Martin Brandl Avatar answered Oct 26 '25 07:10

Martin Brandl


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
like image 39
Major Avatar answered Oct 26 '25 07:10

Major



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!