Skip to main content

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.

If you need dedicated infrastructure for Windows applications and PowerShell workloads, consider a Netherlands Dedicated Server for greater control over scripting, text processing, system configuration, and server resources.

Help Category