PowerShell Replace Method And Operator: Syntax, Examples

Photo of author

By Victor Ashiedu

Published

You can use PowerShell Replace to replace characters, strings, texts, or special characters. PowerShell has a Replace Method and a Replace Operator.

This Itechguide teaches you how to use PowerShell Replace Method and Replace Operator to perform various replace tasks.

The guide has 2 sections. The first section covers the Replace Method with multiple examples.

Then, on the second section, you will learn how to use the Replace Operator, also with multiple examples.

How To Use PowerShell Replace Method With Multiple Examples

How To Use PowerShell Replace Method With Multiple Examples

As I mentioned in the introduction, this section teaches you how to use the Replace Method. The section starts with the syntax of the the Replace Method.

Syntax Of The PowerShell Replace Method

The syntaxes of the Replace Method is…

("string to replace").Replace(char oldChar, char newChar)
("string to replace").Replace(string Replace(string oldValue, newValue)

The syntaxes are does the same thing. The only reason I have both is to illustrate that you can replace characters or strings.

The first syntax shows how to use the PowerShell Replace Method to replace characters. However, the second syntax shows how to replace a string.

How To List The Methods In A PowerShell Object

I already mentioned that PowerShell has a Replace Method and Operator. You can list all Methods available in a PowerShell object by pipping the object to the Get-Member command.

For example, to find the “Methods” available in this object, run the command below:

"this is test" | Get-Member 

The command returns a bunch of Methods. I have highlighted the Replace Method in the screenshot below.

Additionally, there is another way to run the Get-Member command. Instead of pipping the object into the Get-Member command, you can specify the object in the InputObject parameter of Get-Member.

Here is an example…

Get-Member -InputObject "this is test"

The result also list a number of Methods available in the object – including the Replace Method.

How To Use PowerShell Replace Method With Multiple Examples

One last thing before I move on to the next sub-section, if you look at the “Description” column of the result of the last two commands, it has the syntax of the Method.

This is very useful as it tells you how to use the Method.

How To Use PowerShell Replace Method To Replace A Character In A String

I mentioned in the Syntax sub-section that you can replace characters or strings. To give you a simple example, I want to replace “V” in “Victor” with small letter “v”.

Here is the command…

("Victor").Replace("V","v")

And here is the result in PowerShell…

The values in the PowerShell Replace Method are case-sensitive. The values will check for the exact character case. For example, if I tried to replace lower case “v” in “Victor” and try to replace it with “A”, the command will return the same result.

Here is the command I described in the note above…

("Victor").Replace("v","A")

When I ran this command in PowerShell, it returned “Victor”, the original object because there is no lower case “v” in the string, “Victor”!

In the PowerShell Replace Operator section of this guide, you will learn that – unlike the Replace Method – the Replace Operator is case-insensitive.

How To Use PowerShell Replace Method To Replace Multiple Strings In A Text File

Following on from the thoughts in this guide, you can also replace multiple strings in a text file.

In this example, I have a text file with some server names. Here is a screenshot of the text file.

How To Use PowerShell Replace Method To Replace Multiple Strings In A Text File

I want to replace the server name, “ITGServer1” with “ITGServer4”. Additionally, I want to replace “ITGServer2” with “ITGServer5” and “ITGServer3” with “ITGServer6”.

Here is the script that will do the task…

Get-Content E:\reports\ITGServers.txt | ForEach-Object {
   #this command chains the Replace Method.
   #If Replace is run individually, the previous lines appear not to be replaced
 $_.Replace("ITGServer1","ITGServer4").Replace("ITGServer2","ITGServer5").Replace("ITGServer3","ITGServer6")
 }

The first line of the script uses Get-Content to import the content of the text file into PowerShell. Then, pipes the result to ForEach-Object.

Finally, within the ForEach-Object loop, PowerShell uses the athematic variable, $_ created for each object by ForEach-Object to Replace the items as specified.

I have “chained” the PowerShell Replace Method. Otherwise, the script produces an undesirable result.

To run the script copy it to PowerShell ISE and run it.

In the last version of the script, PowerShell displays the result in the console. You can write the output by pipping the existing commands to the Set-Content command.

Here is the updated script. To avoid write errors, I saved the output of the previous version of the script to a variable. Then, I piped the variable into Set-Content command.

$newfile = Get-Content E:\reports\ITGServers.txt | ForEach-Object {
   #this command chains the Replace Method.
   #If Replace is run individually, the previous lines appear not to be replaced
 $_.Replace("ITGServer1","ITGServer4").Replace("ITGServer2","ITGServer5").Replace("ITGServer3","ITGServer6")
 } 
$newfile | Set-Content E:\reports\ITGServers.txt -Force

Here is the output of the new text file…

How To Use PowerShell Replace Method To Replace Multiple Strings In A Text File

How To Use PowerShell Replace Method To Replace Multiple Characters

The processing of replacing multiple strings in a text file is the same as replacing multiple characters in a string. From the example in the last section, it is better to “chain” the Replace Method.

In this example, I want to replace the “M” in “Method” to “T”. Additionally, I want to replace “d” with “D”.

Here is the command…

(("Method").Replace("M","T")).Replace("d","D")

And the result in PowerShell…

How To Use PowerShell Replace Method In Pipeline

In the last section, I ran this command without piping the string, “Method” to the Replace Method:

(("Method").Replace("M","T")).Replace("d","D")

I can run the same command, but this time pipe the string to the Replace Method. However, once I pass it to a pipeline, I have to call the string with the pipeline automatic variable, $_.

The commmand will have to be modified as shown below:

"Method" | Where-Object {$_.Replace("M","T").Replace("d","D")}

As you can see from the screenshot below, the last command produces the same result as the command in the last sub-section…

How To Use PowerShell Replace Method In Pipeline

How To Use PowerShell Replace Method To Replace All Strings After A Character

In the example in this sub-section I wan to to replace everything after the last backslash, “\” in this string – “c:\programfiles\tv\version8\uninstall.exe” – with an empty string.

These two commands will do the job.

$string = "c:\programfiles\tv\version8\uninstall.exe"
 $string.Replace("\uninstall.exe","")

The first command saves the string in a variable. Then, the second command uses the PowerShell Replace Method to replace everything after the string “\” with an empty space.

Effectively, everything after “\” is deleted. Here is the result of the commands..

How To Use PowerShell Replace Method To Replace A String In A Text File

I have a text file called Processfile1.txt. The text file has a value, “AgentSvc” that I want to replace with “AgentSvc_New”.

How To Use PowerShell Replace Method To Replace A String In A Text File

The commands below will complete the task…

$file = "E:\reports\Processfile1.txt"
$find = "AgentSvc"
$replace = "AgentSvc_New"
(Get-Content $file).replace($find, $replace) | Set-Content $file

The first command saves the file path to a variable. Also, the second command saves the value I want to find in another variable.

Additionally, the third line saves the replace string in another variable. Finally, in the last command, I call the Replace Method in the result of the Get-Content command.

Then, within the Replace Method, I use the value saved in the $find and $replace variables. Then, pipe the output to Set-Content that updates the text file with the new values.

After running the commands, here is the new value in the text file.

How To Use PowerShell Replace Method To Replace Double Quotes With Single Quotes

In this subsection, I want to replace the double quote in 234″”20.1.2021 with single quotes. Here are the commands…

$string = '234""20.1.2021'
$string.Replace('""',"''")

The first line saves the string, 234″”20.1.2021 in a variable. Then, in the second line, I used the PowerShell Replace Method to replace the double quote in the string with single quotes.

The trick is in the application and use of PowerShell quoting rules. PowerShell uses both single and double quotes to specify a literal string.

In this example, we want to replace double quotes, “”, in a string with a single quotes, ”. However, if you recollect, in PowerShell Replace Method, you also need quotes to specify the value you want to replace and the new value.

So, to specify the current value (the double quotes) in the Replace command, we wrap the double quote in single quotes – ‘””‘.

Moreover, to specify the new value (the single quotes), you wrap them in double quotes – “””.

Also, because of the presence of double quotes in the original string, 234″”20.1.2021, to save the string in a variable, I had to wrap the string in single quotes.

Going back to the commands…

$string = '234""20.1.2021'
$string.Replace('""',"''")

Here is the result in PowerShell…

How To Use PowerShell Replace Method To Replace Double Quotes With Single Quotes

As simple as this example looks, if you do not understand PowerShell quoting rules, you will struggle to get PowerShell to complete this task!

How To Use PowerShell Replace Method To Replace Exact Match

This section offers another PowerShell Replace Method example. This time, I want to teach you how to replace an exact match in a string.

The example in this section is from this Stackoverflow.com thread. The user that posted the question wants to replace “tea” in this string, “I brought tea for my team” with “coffee”.

Here is the command that does the job…

("I brought tea for my team").Replace("tea","coffee")

And here is the result of the command in PowerShell…

How To Use PowerShell Replace Method To Replace Backslash (\)

In this sub-section, I will replace the single backslash, (\) in this string, 234\20.1.2021 with double backslash, (\\). Here is the command…

("234\20.1.2021").Replace("\","\\")

The result in PowerShell…

How To Use PowerShell Replace Method To Replace Backslash (\)

As you will see in the PowerShell Replace Operator section of this guide, replacing single backslash with Replace Operator is not this straightforward.

How To Replace Invalid Filename Characters In PowerShell

Windows Operating System has some characters that cannot be used to name files or folders. These characters are generally called invalid filename characters.

If you try to create a file name with any of the characters, you will receive an error.

So, if you write a PowerShell script that uses some output to create a filename but these outputs contain any of the invalid filename characters, you have to remove those characters.

The script discussed in this sub-section does not use the PowerShell Replace method. However, I decided to include it because I believe it fixes a unique problem most SysAdmins may face.

Moving on, I got the example I will discuss shortly from this Stackoverfolow.com question. The user that asked the question wants to remove invalid characters from a string before using the string to create a file.

Additionally, if the string contains spaces, the user wants to retain the spaces in the file name.

I took a look at the solutions preferred by different users. The one with the best solution was posted by John Longmuir.

In John’s example, he wants to remove all invalid filename characters in the string, ‘abc*\ def.txt’. However, as requested by the original question author, he wants to retain the spaces in the string.

Here is John’s script…

$name = 'abc*\ def.txt'
([char[]]$name | where { [IO.Path]::GetinvalidFileNameChars() -notcontains $_ }) -join ''

In the first command, he saves the string in a variable. Then, in the first part of the second command (before the pipeline), he converts the $name variable into a [char] datatype.

The [char] datatype is a Unicode 16-bit character.

In the second part of the command, John pipes the output of the converted [char] datatype to a Where-Object command. Within the Where-Object script block, he calls the GetinvalidFileNameChars() Method of the Path Class, [IO.Path].

Then, tells PowerShell to return only values “not contained” in the GetinvalidFileNameChars() Method.

The GetinvalidFileNameChars() Method lists all invalid filename characters.

Finally, after the invalid filename characters have been removed, he uses PowerShell Join to make all characters into a string.

The final result is…The special (invalid filename characters) are gone, but the string is returned with the spaces!

To make it easy to use, and based on the original script posted by the Stackoverfolow.com question author, I decided to turn John’s script into a PowerShell Function.

Here is the PowerShell Function, Remove-InvalidFileNameChars.

Function Remove-InvalidFileNameChars {
 param(
     [Parameter(Mandatory=$true,
     Position=0,
     ValueFromPipeline=$true,
     ValueFromPipelineByPropertyName=$true)]
     [char[]]$Name
 )
 ($name | Where-Object { [IO.Path]::GetinvalidFileNameChars() -notcontains $_ }) -join ''
 }

How To Use PowerShell Replace Operator With Multiple Examples

How To Use PowerShell Replace Operator With Multiple Examples

In the first section of this guide, I covered different examples of PowerShell Replace Method. In this section, I will focus on PowerShell Replace Operator.

The section starts by discussing the syntax of PowerShell Replace Operator.

Syntax Of The PowerShell Replace Operator

The syntax of PowerShell Replace Operator is…

("string to replace") -Replace(char oldChar, char newChar)
("string to replace") -Replace(string Replace(string oldValue, newValue)

One clear difference between a PowerShell Method and an Operator is the way they are used. In a Method, you place a period (.) next to the object, followed by name of the Method and () brackets.

On the contrary, for a Operator, you add a space after the PowerShell object, followed by – and the name if the operator.

So, in the examples that follow, instead of using .Replace(), I will be using -Replace!

How To Use PowerShell Replace Method To Operator A Character In A String

To replace the character “i” with “I” in the string, “Victor”, I will use the command below…

("Victor") -Replace("i","I")

The result in PowerShell…

Unlike, PowerShell Replace Method that is case-sensitive, PowerShell Replace Operator is not. So, the command below, will produce the same result as the previous command…

("Victor") -Replace("I","I")

This time, I used a capital “I” on the value side of Replace operator. Note that there is no capital “I” in the string, “Victor”.

So, if you are writing a PowerShell script that needs to replace upper and lower characters, use the Replace Operator instead of the Replace Method.

How To Use PowerShell Replace Method To Replace Multiple Strings In A Text File

In the Replace Method section, I gave an example where I replaced server names in this text file.

How To Use PowerShell Replace Method To Replace Multiple Strings In A Text File

I want to replace the server name, “ITGServer1” with “ITGServer4”. Additionally, I want to replace “ITGServer2” with “ITGServer5” and “ITGServer3” with “ITGServer6”.

Here is the Replace Operator version of the script used in the Replace Method example…

Get-Content E:\reports\ITGServers.txt | ForEach-Object {
 #this chains the Replace Operators
 (($_ -Replace("ITGServer1","ITGServer4")) -Replace("ITGServer2","ITGServer5")) -Replace("ITGServer3","ITGServer6")
 }
Like we did in the Replace Method example, the Replace Operator part of the last script is “chained”.

How To Use PowerShell Replace Operator To Replace Case Sensitive Strings And Characters

At various points in this guide, I have hinted that PowerShell Replace Method is case-sensitive. However, PowerShell Replace Operator is not.

In this section I want to illustrate with an example.

For example, this command will NOT replace R because the Replace Method is case sensitive.

("R").Replace("r","b") 

However, this commmand will replace R because Replace Operator is NOT case sensitive by default

("R") -Replace("r","b")
How To Use PowerShell Replace Operator To Replace Case Sensitive Strings And Characters

How To Use PowerShell Replace Operator To Replace Backslash (\)

In the first section of this guide, I used this PowerShell command to replace the single backslash, (\) in this string, 234\20.1.2021, with double backslash, (\\)…

("234\20.1.2021").Replace("\","\\")

As you can see, I simply used the single backslash “\” in the Replace Method without any problem.

However, if I turn the last command into the Replace Operator version, I will receive an error message. Here is the Replace Operator version of the command:

"234\20.1.2021" -Replace("\","\\")

If I run the command in PowerShell, I will receive an error message…

The reason for this error is because in PowerShell, “\” is treated as a regular expression pattern. To overcome this problem, I need to add a second backslash in “\”.

This will make the single backslash in “\”, appear like double, “\\”. However, the second backslash is telling PowerShell not to treat “\” as a regular expression pattern.

So the command will now be..

"234\20.1.2021" -Replace("\\","\\")

Now the command works like a charm!

That is it – a comprehensive and revamped PowerShell Replace guide!

I hope this post was helpful to you. If the post was of any help to you, kindly take a few minutes to tell us what you think at [discourse_topic_url].

However, if you have any questions regarding this article please post your question at [discourse_topic_url]. Our team and other community members will come back to you with a reply as soon as possible.

Finally, for more PowerShell tech Itechguides, visit our Windows PowerShell How-To guide page. You may also find our Work from Home page very helpful.

References and Further Reading

  1. About methods
  2. About Operator
  3. about_Quoting_Rules
  4. How-to: Define PowerShell Data Types
  5. Path Class
  6. How to Extract a Powershell Substring from a String
  7. Powershell If Else Explained: Syntax and Examples

About the Author

Photo of author

Victor Ashiedu

Victor is the founder of InfoPress Media, publishers of Ilifeguides and Itechguides. With 20+ years of experience in IT infrastructure, his expertise spans Windows, Linux, and DevOps. Explore his contributions on Itechguides.com for insightful how-to guides and product reviews.

Related Articles

Get in Touch

We're committed to writing accurate content that informs and educates. To learn more, read our Content Writing Policy, Content Review Policy, Anti-plagiarism Policy, and About Us.

However, if this content does not meet your expectations, kindly reach out to us through one of the following means:

  1. Respond to "Was this page helpful?" above
  2. Leave a comment with the "Leave a Comment" form below
  3. Email us at [email protected] or via the Contact Us page.

4 thoughts on “PowerShell Replace Method And Operator: Syntax, Examples”

  1. Hi Victor,

    In the following filename example I want to replace the 25th character which is a _ with a space ‘ ‘ character and also the 31st character again the ‘_’ with a space ‘_’

    SomeListReport-XXXX-Roll_00001_01_11_2021-10_55_27.zip

    I have the code to find the characters but cant get the .Replace working
    I do not want to change any of the other characters in the filename only the 25th and 31st characters.

    Many thanks in advance for any assistance
    Neil

    Reply
  2. How do i replace text using a wildcard character?

    e.g.
    Current string value =
    This is my test value string 123456.tgf457

    I want to replace .tgf457 with just a “.

    New string value should =
    This is my test value string 123456”

    Thanks

    Reply
    • Hi Jack,

      The first step is to split 123456.tgf457 and remove everything after the period (.)

      Then, use Replace to replace the period (.) with (“).

      Here are the commands

      1. $var = (“123456.tgf457”).Substring(0,7)

      This command saves the output 123456. in the $var variable.

      The second command is to use Replace to replace . with ” – here is the command –

      2. $var.Replace(‘.’, ‘”‘)

      This command will return 123456”

      Lead more about split – https://www.itechguides.com/powershell-substring/

      Reply

Leave a comment

Send this to a friend