How to Replace Backslash Characters in PowerShell


Often you may want to replace backslash characters in a string in PowerShell.

You can use the following methods to do so:

Method 1: Replace single backslash with some other character

$original_string -replace '\\', '-'

This particular example will replace all text before ‘web’ in the string variable named original_string.

Method 2: Replace double backslash with single backslash

$original_string -replace '\\\\', '\'

Method 3: Replace single backslash with double backslash

$original_string -replace '\\', '\\'

Note: When using the -replace operator to replace backslashes, we must use a backslash as an escape character.

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

Example 1: Replace Single Backslash with Some Other Character in PowerShell

We can use the following syntax to replace a single backslash with a dash in PowerShell:

$original_string = "c:\some\file\path"
$original_string -replace '\\', '-'

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

PowerShell replace backslash with other character

Notice that each backslash in the original string has been replaced with a dash instead.

The original string was: c:\some\file\path

The new string is: c:-some-file-path

Example 2: Replace Double Backslash with Single Backslash in PowerShell

We can use the following syntax to replace a double backslash with a single backslash in PowerShell:

$original_string = "c:\\some\\file\\path"
$original_string -replace '\\\\', '\'

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

PowerShell replace double backslash with single backslash

Notice that each double backslash in the original string has been replaced with a single backslash instead.

The original string was: c:\\some\\file\\path

The new string is: c:\some\file\path

Example 3: Replace Single Backslash with Double Backslash in PowerShell

We can use the following syntax to replace a single backslash with a double backslash in PowerShell:

$original_string = "c:\some\file\path"
$original_string -replace '\\', '\\'

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

PowerShell replace single backslash with double backslash

Notice that each single backslash in the original string has been replaced with a double backslash instead.

The original string was: c:\some\file\path

The new string is: c:\\some\\file\\path

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 Multiple Strings in File
PowerShell: How to Replace Text in String

Leave a Reply