24/7/365 Support

Replace Text in a String in Windows PowerShell

Problem

You want to replace a portion of a string with another string.

Solution

PowerShell provides several options to help you replace text in a string with other text.

Use the Replace() method on the string itself to perform simple replacements:

PS >"Hello World".Replace("World", "PowerShell")

Hello PowerShell Use PowerShell’s regular expression –replace operator to perform more advanced regular expression replacements:

PS >"Hello World" replace '(.*) (.*)','$2 $1' World Hello

Discussion

The Replace() method and the –replace operator both provide useful ways to replace text in a string. The Replace() method is the quickest but also the most constrained. It replaces every occurrence of the exact string you specify with the exact replacement string that you provide. The –replace operator provides much more flexibility, since its arguments are regular expressions that can match and replace complex patterns.

The regular expressions that you use with the –replace operator often contain characters that PowerShell normally interprets as variable names or escape characters. To prevent PowerShell from interpreting

these characters, use a nonexpanding string (single quotes) as shown by the solution.

Help Category:

Get Windows Dedicated Server

Only reading will not help you, you have to practice it! So get it now.

Processor RAM Storage Server Detail
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 128 GB (SSD SATA) Configure Server
Intel Atom C2750 2.4 GHz 8c/8t 8 GB DDR3 1× 1 TB (HDD SATA) Configure Server
Intel Xeon E3-1230 v2 3.3 GHz 4c/8t 16 GB DDR3 1× 256 GB (SSD SATA) Configure Server
Intel Atom C2350 1.7 GHz 2c/2t 4 GB DDR3 1× 250 GB (SSD SATA) Configure Server

What Our Clients Say