Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using Powershell Get-Content, how do you replace a string with a backslash

Tags:

powershell

In powershell if you have a string such as

Server\MyName

how to you replace it with

MyOtherServer\AnotherName

I have tried escaping with ' and using single quotes but that doesn't seem to work

like image 275
Kev Hunter Avatar asked Jan 30 '26 22:01

Kev Hunter


2 Answers

There is the -replace operator, but it takes a regular expression (so you have to escape backslashes):

$s -replace 'Server\\MyName', 'MyOtherServer\AnotherName'

Of course, the necessary escaping only applies to the regex, not the replacement.

like image 95
Joey Avatar answered Feb 02 '26 15:02

Joey


You can also use the Replace method, it doesn't require you to escape slashes:

$s.Replace('Server\MyName','MyOtherServer\AnotherName')
like image 43
Shay Levy Avatar answered Feb 02 '26 13:02

Shay Levy