Like many other languages out there, PowerShell can work with strings and text. One of those useful features is to use PowerShell to replace characters, strings, or even text inside of files.
Not a reader? Watch this related video tutorial!In this tutorial, you’re going to learn how to use the PowerShell replace()
method and PowerShell replace
operator. The tutorial will cover the basics and even dive into some “fun” regular expressions!
You won’t need much to follow along with all of the examples in this tutorial; you’ll just need PowerShell. This tutorial examples will be using PowerShell v7.0.2 but all examples should work in Windows PowerShell.
Using PowerShell to Replace Strings: The Basics
One of the simplest cases of using PowerShell replace is to replace characters in strings. Let’s start there with some examples.
Let’s say you have a string in PowerShell with a value of hello, world
.
$string = 'hello, world'
You’d like to replace the string hello
, inside of that string with the string hi
to make the $string
variable have a value of hi, world
. To do that, PowerShell first needs to figure out where the “find” text. Once it’s found, it then replaces that text with a user-defined value.
Using the Replace()
Method
One of the easiest ways to replace strings in PowerShell replace command method as shown below. The replace()
method has two arguments; the string to find and the string to replace the found text with.
As you can see below, PowerShell is finding the string hello
and replacing that string with the string hi
. The method then returns the final result which is hi, world
.
PS> $string.replace('hello','hi')
hi, world
You can call the PowerShell replace method on any string to replace any literal string with another. If the string-to-be-replaced isn’t found, the replace()
method returns nothing.
You don’t need to assign a string to a variable to replace text in a string. Instead, you can invoke the
replace()
method directly on the string like:'hello world'.replace('hello','hi')
. The tutorial is using a variable for convenience.
Removing Characters
Maybe you want to remove characters in a string from another string rather than replacing it with something else. You can do that too by specifying an empty string.
PS> $string.replace('hello','')
, world
Replacing Multiple Instances
You now have the code to replace a string inside of another string. What about replacing multiple strings? No problem.
Since the PowerShell replace method returns a string, to replace another instance, you can append another replace()
method call to the end. PowerShell then invokes the replace()
method on the output of the original.
PS> $string.replace('hello','').replace('world','earth')
, earth
You can chain together as many
replace()
method calls as necessary but you should look into using thereplace
operator if you have many strings to replace.
Using the PowerShell Replace Operator
Although using the PowerShell replace string method is the simplest way to replace text, you can also use the PowerShell replace
operator. The replace
operator is similar to the method in that you provide a string to find and replace. But, it has one big advantage; the ability to use regular expressions (regex) to find matching strings (more later).
Using the above example, you can use the replace
operator to replace hello
with hi
in a similar fashion as shown below. PowerShell performs the same steps.
PS> $string -replace 'hello','hi'
hi, world
Removing Characters
Like the PowerShell replace method, you can also remove characters from a string using the replace
operator. But, unlike the replace()
method, you can also completely exclude the string as an argument to replace with and you’ll discover the same effect.
PS> $string -replace 'hello',''
, world
PS> $string -replace 'hello'
, world
Replacing Multiple Instances
Like the replace()
method, you can also chain together usages of the replace
operator. Since the replace
operator returns a string as shown below. You’ll see in the next section, your code will be cleaner using regex.
PS> $string -replace 'hello','hi' -replace 'world','earth'
hi, earth
Using PowerShell Regex Replace
As mentioned above, replacing strings in PowerShell replace method works but it’s limited. You are constrained to only using literal strings. You cannot use wildcards or regex. If you’re performing any kind of intermediate or advanced replacing, you should use the replace
operator.
Let’s say you have a script that contains a string that is created with a variable. That string should either be hello, world
or hi, world.
Maybe you have had a bad day as a sysadmin and want to change the string, regardless of the value, to goodbye, world
.
You need hello, world
and hi, world
to both be transformed to goodbye, world
. To make this happen, you need to use a regular expression. You can match just about any specific pattern in text with regex.
In this example, you can use the expression hello|hi
to match both required strings using the regex “or” (|
) character as you can see below.
PS> 'hello, world' -replace 'hello|hi','goodbye'
goodbye, world
PS> 'hi, world' -replace 'hello|hi','goodbye'
goodbye, world
Once you learn how to wield regex to find strings, you can use PowerShell to replace wildcard strings that match any pattern.
Escaping Regex Characters
In the regex example above, the string to search in did not contain any regex special characters. The regular expression language has certain characters it uses that are not interpreted literally like most letters and numbers.
For example, perhaps you need to replace text in a string. That string contains a couple of regex special characters like a bracket and a question mark. You then try to replace the string [hello]
with goodbye
as shown below.
PS> '[hello], world' -replace '[hello]','goodbye'
[goodbyegoodbyegoodbyegoodbyegoodbye], wgoodbyergoodbyed
That’s clearly not what you intended. This scenario happens when you use regex special characters inside of the string to find ([hello]
).
To avoid this problem, you have two options. You can either escape these special characters by prepending a backslash to the front of each character or use the Escape()
method.
Below you can see the effect of escaping each special character with a backslash.
PS> '[hello], world' -replace '\[hello\]','goodbye'
goodbye, world
Alternatively, and recommended, you can use the regex type’s Escape()
method to automatically remove all special characters.
PS> '[hello], world' -replace ([regex]::Escape('[hello]')),'goodbye'
goodbye, world
You should use the
Escape()
method where possible because it will escape all special characters so you don’t have to remember them.
Using Match/Capture Groups
In all of the previous examples, this tutorial has been using a literal string to replace another string with. You’ve been using hi
or goodbye
. But what if you want to use one or more characters that PowerShell found in the string to replace with? You’ll need to match or capture groups.
Regex has a concept called capture groups and backreferences. Capture groups allow you to capture strings to then reference elsewhere. PowerShell leverages this features by using match groups with the replace
operator.
For example, perhaps you have a string that could contain a few different values.
'hello world, you sexy beast'
'hi world, now go away'
'hello earth, you are lovely today'
You’d like to swap the first part of the string with the second part making them look like this:
'you sexy beast,hello world'
'now go away,hi world'
'you are lovely today,hello earth'
To perform this action, PowerShell must find all of the text to the right and left of the comma. Once it knows what that text is, it must then replace one with the other. To do that, you need backreferences.
A backreference is a regex variable (not a PowerShell variable) that represents the text that regex matched. Backreferences in PowerShell are represented with a dollar sign followed by a number indicating the order in which they were matched.
You can see an example below.
## This string could also be:
## 'hi, world, now go away'
## 'hello, earth, you are lovely today'
PS> $string = 'hello, world, you sexy beast'
PS> $string -replace '(.*), (.*)','$2,$1'
you sexy beast,hello world
In the above example, you can see regex capture groups enclosing each match (hello world
) and (you sexy beast
) with parentheses. Then, for the replacement, hello word
was matched first from left to right so it gets a $1
backreference label and you sexy beast
gets a $2
backreference label.
Once PowerShell knows the value for each match, you can use these references in the replaced text in any way you’d like. In this example $2,$1
swaps their positions.
Using Named Match Groups
If you’d rather not use number placeholders like $1
, $2
to reference match values, you can use labels or names too. Instead of having to count from left to right which references mean what, you can simply use names.
To use names as references, you need to first define labels for each match in the match string. To do that, you must define the capture group like (?<label><regex>)
where label
is the name and <regex>
is the regular expression you are using.
Once you’ve defined the names, you can then reference them in the replace string using a dollar sign and enclosing the name in curly braces e.g. ${label}
.
You can see a demonstration of this technique below.
PS> $string = 'hello, world, you sexy beast'
PS> $string -replace '(?<First_Part>.*), (?<Second_Part>.*)','${Second_Part},${First_Part}'
you sexy beast,hello, world
Conclusion
As you’ve learned, PowerShell replace operator allows you to replace characters, text and strings many different ways. To perform simple replacements, you can use the replace()
method but if you need to match and replace anything more advanced, always use the replace
operator.