PowerShell: How to Use Case-Insensitive Replacement


You can use the -replace operator to perform a case-insensitive replacement in PowerShell:

$original_string -replace "ZACH", "Andy"

This particular example will replace the string “Zach” with the string Andy in the string variable named $original_string, regardless of case.

This means that variations such as ZACH, Zach and zach would all be replaced with Andy in this scenario.

By contrast, the Replace() method is case-sensitive and will only perform a replacement if an exact matching case is found.

The following example shows how to use the -replace operator in practice.

Example: How to Use Case-Insensitive Replacement in PowerShell

Suppose we create a string variable named $original_string in PowerShell that contains the following string:

  • “My name is Zach”

Suppose we attempt to use the Replace() method to replace “ZACH” with “Andy” instead:

$original_string = "My name is Zach"
$original_string.Replace("ZACH", "Andy")

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

Notice that no replacement is made because the text “ZACH” does not match the case of “Zach” in the string variable.

To perform a case-insensitive replacement, we must use the -replace operator instead:

$original_string = "My name is Zach"
$original_string -replace "ZACH", "Andy"

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

PowerShell case-insensitive replacement

Notice that “Zach” has been replaced with “Andy” because we used a case-insensitive replacement this time.

Note that you could also use the -ireplace operator to make the replacement explicitly case-insensitive:

$original_string = "My name is Zach"
$original_string -ireplace "ZACH", "Andy"

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

PowerShell -ireplace operator

Once again, “Zach” has been replaced with “Andy” because we used the -ireplace operator to perform a case-insensitive replacement.

Note: You can find the complete documentation for the -replace and -ireplace operators in PowerShell here.

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