How To Use Powershell Replace Text Operator / String – 3 Best Ways

Windows PowerShell is a command-line shell and scripting language intended primarily for system administration. In Linux, it has a counterpart known as Bash Scripting.

How To Use Powershell Replace Text Operator / String - 3 Best Ways 

You will learn how to use the PowerShell replace () method and the PowerShell replace operator in this lesson. In addition to covering the fundamentals, the course will also explore some “fun” regular expressions.

How To Use Powershell Replace Methods

  1. Use Powershell Replace Operator
  2. Using The Replace() Method
  3. Using Powershell Regex Replace

Using Powershell To Replace Strings: The Basics

The replacement of characters in strings is one of the simplest uses of PowerShell replace.

Say you have a PowerShell string with the value “HELLO, WORLD?”

$string = ‘HELLO, WORLD’

  • To give the $string variable the value “HII, WORLD,” you’d like to swap out the string “HELLO” for the string “HII” inside of that string.
  • PowerShell must first locate the “find” text in order to accomplish it.
  • When it does, it then swaps out the text with a value that the user has specified.

Use Powershell Replace Operator -replace

The PowerShell replace characters operator can also be used to replace script, though the PowerShell replace string technique is the simplest. In that you supply a string to search and replace, the replace operator is comparable to the method in that respect.

One significant benefit is the capability to find matched texts using regular expressions (regex) (more later).

In a similar manner, hello can be replaced with HII using the replace operator.

PS> $string -replace ‘hello’,’hi’

HII, WORLD

1. Removing Characters

The PowerShell replace operator can be used to remove characters from a string just like the PowerShell replace function does.

In contrast to the replace() method, you can also completely exclude the string from the list of arguments to replace with and get the same result.

PS> $string -replace ‘hello’,”

, world

PS> $string -replace ‘hello’

, world

2. Replacing Multiple Instances

The replace operator can be used in a chained fashion, just as the replace() method. Due to the fact that the replace operator returns a string, as displayed below. Your code will be cleaner if you use regex, as you’ll see in the following section.

PS> $string -replace ‘HELLO’,’HII’ -replace WORLD,’PEOPLE’

HII, PEOPLE

Using The Replace() Method

One of the simplest methods for replacing strings in PowerShell is using the replace command. The string to be found and the string to use in lieu of the found text are the two arguments given to the replace() method.

The string “HELLO, WORLD?” is being located by PowerShell and replaced with the string “What are you”. The final result, which is “HII, WORLD”, is then returned by the method.

$string.replace(HELLO,’HII’)

Any literal string can be replaced with another by calling the PowerShell replace method on it. The replace() method does not return anything if the string-to-be-replaced cannot be found.

1. Removing Characters

You may want to remove characters from another string rather than replacing it with another word or phrase. Do this by typing in an empty string.

PS> $string.replace(HELLO,”)

, WORLD

2. Replacing Multiple Instances

Now that you have the code, you can change one string inside of another. What about swapping out several strings?

  • As the PowerShell replace method returns a string, you can add more calls to the replace() method to replace other instances.
  • The replace() method is then used by PowerShell on the output of the original.

PS> $string.replace(‘hello’,”).replace(‘world’,’earth’)

, earth

Using Powershell Regex Replace

1. Escaping Regex Characters

The search string in the regex example lacked any special regex characters. Some characters used in the regular expression language, unlike the majority of letters and integers, are not read literally.

For instance, you could need to change some text in a string. A bracket and a question mark are two regex special characters that can be found in that string. You then attempt to substitute “goodbye” for the string “hello.”

PS> ‘[hello], world’ -replace ‘[hello]’,’goodbye’

[goodbyegoodbyegoodbyegoodbyegoodbye], wgoodbyergoodbyed

It’s obvious that’s not what you meant. This condition occurs when you search for special characters in a string using regex ([hello]).

You have two choices to get around this issue. By adding a backslash to the front of each character, you can escape these special characters, or you can use the Escape() method.

The results of escaping each special character with a backslash are shown below.

PS> ‘[hello], world’ -replace ‘\[hello\]’,’goodbye’

goodbye, world

As an alternative, and strongly advised, you can automatically eliminate any special characters by using the Escape() method of the regex type.

PS> ‘[hello], world’ -replace ([regex]::Escape(‘[hello]’)),’goodbye’

goodbye, world

2. Using Capture Groups

In this example, a literal string has been used to swap out another string. But what if you want to replace a string with one or more of the characters that PowerShell discovered in it? Groups must be matched or captured.

Capture groups and backreferences are a Regex notion. You can capture strings using capture groups for later use as references. By combining the replace operator with match groups, PowerShell makes use of these features.

You might, for instance, have a string with a range of possible values. The first and second parts of the string should be switched.

PowerShell must locate all of the text to the right and left of the comma in order to carry out this action.

It must then swap out one for the other after determining what that text is. You need backreferences to accomplish that.

A regex variable—not a PowerShell variable—that represents the text that a regex match found is called a backreference. In PowerShell, backreferences are denoted by a dollar sign and a number that denotes the sequence in which they were matched.

PS: $string equals “Hello, world, you are intelligent.”

PS> $string -replace “$2,$1” with “(.*), (.*)”

Hello world, you are intelligent.

You can see that in the aforementioned example, parentheses are used to enclose each match of (hello world) and (you are smart) in regex capture groups. Then, for the replacement, “you are smart” received a $2 backreference label and “hello” received a $1 backreference label for matching first from left to right.

PS> $string = ‘hello, world, you are smart’

PS> $string -replace ‘(.*), (.*)’,’$2,$1′

you are smart,hello world

The references in the altered text can be used in any way once PowerShell is aware of the value for each match. In this illustration, $2 and $1 switch places.

3. Using Named Match Groups

You can also use labels or names to reference match values if you’d prefer not to use numerical placeholders like $1 and $2. You can just use names rather than having to count which references are what from left to right.

You must first establish labels for each match in the match string before you can utilise names as references. For that, you must define the capture group as (?label>regex>), where label denotes the name and regex> denotes the current regular expression.

After defining the names, you can use the dollar sign and curly braces to refer to them in the replace string, as in e.g. ${label}

Meet the Author

Abdul Rahim has been working in Information Technology for over two decades. Learn how Abdul got his start as a Tech Blogger , and why he decided to start this Software blog. If you want to send Abdul a quick message, then visit his contact page here.