PowerShell Snippet: How to replace a string within a text file

English   |   Código fuente

This comes up quite frequently in the scripts I'm writing - how do I use PowerShell to replace a string within a text file. Here's a simple one-liner to do this (well, the example further down is four lines even though it can be done on a single line).

The code in its most simple form:

(Get-Content 'PathToFile').Replace('OldString','NewString') | Set-Content 'PathToFile'

Here's an example I've use to replace the "$env:COMPUTERNAME" in capitals with 'localhost' within an installed application's 'configuration.xml' file:

$InputFile = "${env:ProgramFiles(x86)}\Application\configuration.xml"
$OldString = "net.tcp://$($env:COMPUTERNAME.ToUpper()):8050/Service"
$NewString = 'net.tcp://localhost:8050/Service'
(Get-Content $InputFile).Replace($OldString,$NewString) | Set-Content $InputFile

I hope this is useful for you!