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

Using PowerShell, I want to replace all exact occurrences of [MYID] in a given file with MyValue . What is the easiest way to do so?


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

(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 it's 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. It's the same as $content=content; $content | where ...


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 don't 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.

链接地址: http://www.djcxy.com/p/4954.html

上一篇: 我们何时需要围绕shell变量使用花括号?

下一篇: 如何用PowerShell替换文件中的每个字符串?