How can I replace every occurrence of a String in a file with PowerShell? - Stack Overflow

PHOTO EMBED

Mon Nov 04 2024 01:08:46 GMT+0000 (Coordinated Universal Time)

Saved by @baamn

If (select-string -path "c:\Windows\System32\drivers\etc\hosts" -pattern "String to look for") `
    {(Get-Content c:\Windows\System32\drivers\etc\hosts).replace('String to look for', 'String to replace with') | Set-Content c:\Windows\System32\drivers\etc\hosts}
    Else{"Nothing happened"}
content_copyCOPY

-1 Small correction for the Set-Content command. If the searched string is not found the Set-Content command will blank (empty) the target file. You can first verify if the string you are looking for exist or not. If not it will not replace anything.

https://stackoverflow.com/questions/17144355/how-can-i-replace-every-occurrence-of-a-string-in-a-file-with-powershell