4

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.

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

So is it correct to write always all in one line, if even the line will be too long?
@farag It depends but usually I would try to make a script as readable as possible like avoding aliases and split statements into multiple line. I also provide you a more readable version.
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.