Replace Substring in Powershell

Replace Substring in Powershell

I have a string in the form -content-, and I would like to replace it with &content&. How can I do this with replace in PowerShell?

2 Answers

PowerShell strings are just .NET strings, so you can:

PS> $x = '-foo-'
PS> $x.Replace('-', '&')
&foo&

...or:

PS> $x = '-foo-'
PS> $x.Replace('-foo-', '&bar&')
&bar&

Obviously, if you want to keep the result, assign it to another variable:

PS> $y = $x.Replace($search, $replace)
1

The built-in -replace operator allows you to use a regex for this e.g.:

C:\PS> '-content-' -replace '-([^-]+)-', '&$1&'
&content&

Note the use of single quotes is essential on the replacement string so PowerShell doesn't interpret the $1 capture group.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Robert Thorne
Author

Robert Thorne

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.