Adding and Removing Backslashes

by Jan 25, 2017

For path components, it is often necessary to “normalize” paths and, for example, make sure they all end with a backslash. Some try code like this:

$path = 'c:\temp'
if ($path -notmatch '\\$')
    $path += '\'

A regular expression is used to find a backslash at the end of some text, and if it is missing, a backslash is added.

If you wanted to remove a backslash at the end of a path, you could use -replace directly:

$path = 'c:\temp\' -replace '\\$'

Twitter This Tip! ReTweet this Tip!