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

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

Use (V3 version):

(Get-Content c:temptest.txt).replace([MYID], MyValue) | Set-Content c:temptest.txt

Or for V2:

(Get-Content c:temptest.txt) -replace [MYID], MyValue | Set-Content c:temptest.txt

I prefer using the File-class of .NET and its static methods as seen in the following example.

$content = [System.IO.File]::ReadAllText(c:bla.txt).Replace([MYID],MyValue)
[System.IO.File]::WriteAllText(c:bla.txt, $content)

This has the advantage of working with a single String instead of a String-array as with Get-Content. The methods also take care of the encoding of the file (UTF-8 BOM, etc.) without you having to take care most of the time.

Also the methods dont mess up the line endings (Unix line endings that might be used) in contrast to an algorithm using Get-Content and piping through to Set-Content.

So for me: Fewer things that could break over the years.

A little-known thing when using .NET classes is that when you have typed in [System.IO.File]:: in the PowerShell window you can press the Tab key to step through the methods there.

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

(Get-Content file.txt) | 
Foreach-Object {$_ -replace [MYID],MyValue}  | 
Out-File file.txt

Note the parentheses around (Get-Content file.txt) is required:

Without the parenthesis the content is read, one line at a time, and flows down the pipeline until it reaches out-file or set-content, which tries to write to the same file, but its already open by get-content and you get an error. The parenthesis causes the operation of content reading to be performed once (open, read and close). Only then when all lines have been read, they are piped one at a time and when they reach the last command in the pipeline they can be written to the file. Its the same as $content=content; $content | where …

Leave a Reply

Your email address will not be published. Required fields are marked *