PowerShell - Replace string

by
Jeremy Canfield |
Updated: May 11 2023
| PowerShell articles
replace can be used to replace a pattern. In this example, the $foo variable is updated from "Hello World" to "Goodbye World".
$foo = "Hello World"
$foo = $foo -replace 'Hello', 'Goodbye'
Let's say example.txt contains line "Hello World" and you want to change this to "Goodbye World". Here is a one liner command to replace a pattern in a file.
(Get-Content 'C:\Users\JohnDoe\example.txt') -replace '^Hello.*', 'Goodbye World' | Set-Content 'C:\Users\JohnDoe\example.txt'
Notice in this one liner that the same file is referenced twice (C:\Users\JohnDoe\example.txt). It's a good idea to store the file in a variable to ensure the file being read using Get-Content is the same file being overwritten using Set-Content.
$file = 'C:\Users\JohnDoe\example.txt'
(Get-Content $file) -replace '^Hello.*', 'Goodbye World' | Set-Content $file
Or, as another example, let's say the whoami command returns
> whoami
appl\JohnDoe
Here is how you could remove appl\ from whoami.
$id = (whoami) -replace 'appl\\', ''
Write-Host "id = $id"
Did you find this article helpful?
If so, consider buying me a coffee over at