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 '\\$'
ReTweet this Tip!
Why not use the Join-Path cmdlet to ensure the paths end with a backslash? Like this:
Join-Path -Path c:\temp -ChildPath \
Join-Path will either add or not add the ending backslash based on whether the Path parameter does or does not have the backslash. No need for the if statement, regex notmatch test, or the string concatenation.