Replace Backslash in variable with Powershell

Sometimes when we automate things, some technologies don’t play nice with characters we’ve gotten from a different technology. Case in point, my recent post about documenting your SCOM Distributed Applications, I found a test case where a user entered a backslash in the name of a Distributed Application. When Powershell was trying to enter this name as the name of a sheet in Excel, it was failing to add it correctly. So I needed to replace the backslash in the string with a different character.

The key here is to use  -replace function

With the replace function we can replace any character we want, very simply.
for instance:

$test = "44553" -replace, '4'

Would replace all the 4’s in our variable regardless of their location.

We could further use this by using a variable with our pattern that we want to find and replace.

$pattern = '4'
$test = "44553" -replace $pattern, '5' 

This would output 55553.

The problem, however arises when we need to get rid of a backslash. In Powershell the backslash is an escape character, so we have to double it up.

$pattern = '[\\/]'
$string = "this/is\a/\test"
$string = $string -replace $pattern, '-' 

and we get:

replace backslash with powershell


Hi, I’m Billy York.  I work in Cloud and Datacenter, specializing in monitoring and automation. Here you’ll find posts about System Center Operations Manager, Powershell, Hyper-V, Azure Automation, Azure Log Analytics and other Microsoft related technologies.