Replace Text in Files

by Jun 18, 2010

Often, some text will need to be replaced in a text file. That's easy with Get-Content and Set-Content – or not?

Get-Content c:somefile.txt |
Foreach-Object { $_ -replace 'old', 'new' } |
Set-Content c:somefile.txt

If you try this, PowerShell will complain that the file is in use and can't be written to. PowerShell cannot read and write to a file at the same time. Your solution: use parenthesis so that PowerShell reads the file first and only and then processes the content:

(Get-Content c:somefile.txt) |
Foreach-Object { $_ -replace 'old', 'new' } |
Set-Content c:somefile.txt