How to Replace Text in String in PowerShell (With Examples)


There are two common ways to replace specific text in strings in PowerShell:

Method 1: Use the Replace() method

$original_string.Replace("old_text", "new_text")

Method 2: Use the -replace operator

$new_string = $original_string -replace "old_text", "new_text"

Both of these examples replace “old_text” with “new_text” in the string stored in the variable named original_string.

The following examples show how to use each method in practice.

Example 1: Replace Text in String in PowerShell by Using Replace() Method

One of the most common ways to replace specific text in a string in PowerShell is by using the Replace() method.

For example, we can use the following syntax to replace “great” with “wonderful” in a string variable:

$original_string = "I hope everyone has a great day"
$original_string.Replace("great", "wonderful")

The following screenshot shows how to use this syntax in practice:

PowerShell replace text in string

Notice that “great” has been replaced with “wonderful” in the string.

If you would like to simply remove the text “great” from the string then you can replace the text with nothing instead:

$original_string = "I hope everyone has a great day"
$original_string.Replace("great", "")

The following screenshot shows how to use this syntax in practice:

PowerShell remove text from string

Notice that “great” has simply been removed from the string.

Note: The Replace() method is case-sensitive.

Example 2: Replace Text in String in PowerShell by Using Replace() Method

Another way to replace specific text in a string in PowerShell is by using the -replace operator.

For example, we can use the following syntax to replace “great” with “wonderful” in a string variable:

$original_string = "I hope everyone has a great day"
$new_string = $original_string -replace "great", "wonderful"
$new_string

The following screenshot shows how to use this syntax in practice:

Notice that “great” has been replaced with “wonderful” in the string.

It’s worth noting that the -replace operator is case-insensitive.

If you would like to use a case-sensitive replacement, you can use the -creplace operator instead.

For example, we can use the following syntax to attempt to replace “Great” with “wonderful” in the string:

$original_string = "I hope everyone has a great day"
$new_string = $original_string -creplace "Great", "wonderful"
$new_string

The following screenshot shows how to use this syntax in practice:

PowerShell case-sensitive replace text in string

Notice that the text “great” has not been replaced because it doesn’t match the case of “Great” that we searched for using the -creplace operator.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Replace Every Occurrence of String in File
PowerShell: How to Replace Special Characters in String
PowerShell: How to Concatenate Strings

Leave a Reply