Note. This solution is of interest only if you need to trim no more than two tags \ . You also want to support path delimiters / , want to handle root paths correctly, or are generally interested in regular expression methods.
If it is permissible to trim any non-empty mileage at the end of \ characters, i.e. also 3 or more (which is quite likely in this case), and the root paths do not require special treatment, use Martin Brandl a simple solution .
PowerShell-based solution -replace operator with a regex that handles both trailing \ and \\ , and also works with / , given that PowerShell accepts both \ and / as a path separator (which will also work with PowerShell Core version of Cross-Platfom): [1]
[\\/] is a character class ( [...] ) that matches a single character that is either \ (escaped as \\ to process as a literal) or / .
[\\/]?[\\/] matches one or two copies \ at the end of the ( $ ) line, [\\/]+ more weakly matches one or more ( + ).
Without specifying a replacement string, effectively removes the match from the string; if there is no match, the input string remains as-is.
To demonstrate that the approach works with various paths, including UNC paths:
'C:\Ravi', 'C:\Ravi\', 'C:/Ravi/', 'C:\Ravi\\', '\\foo\bar\', 'C:\', '\' | % { $_ -replace '[\\/]?[\\/]$' }
The above gives:
C:\Ravi C:\Ravi C:/Ravi C:\Ravi \\foo\bar C:
Note, however, that root path processing is problematic : C:\ was converted to C: and \ led to an empty string.
Fixing that - leaving the final \ in these special cases - requires a much more complicated regular expression (slightly simplified by matching any number of dividers of the trading path):
'C:\Ravi', 'C:\Ravi\', 'C:\', 'C:\\', '\', '\\' | % { $_ -replace '(?:^((?:[az]:)?\\)\\*$)|(.*?)(?:\\+)$', '$1$2' }
This gives:
C:\Ravi C:\Ravi C:\ C:\ \ \
Notice how the root paths (one) \ end now.
The special shell of the root paths is cumbersome, which is why it is sometimes preferable to provide rather than delete trailing \ or / (for example, C:\Ravi → C:\Ravi\ ) in order to facilitate the creation of paths with simple string concatenation (without worrying about doubling characters \ ). regex will become simple again:
'C:\Ravi', 'C:\Ravi\', 'C:\', 'C:\\', '\', '\\' | % { ($_ -replace '[\\/]+$') + '\' }
This gives:
C:\Ravi\ C:\Ravi\ C:\ C:\ \ \
Notice how all paths end (one) \ .
[1] String manipulation is sometimes required, but often you can rely on the Join-Path cmdlet to build paths for you, which gracefully handles the final \ part of the directory (for example, Join-Path C:\Ravi\ file.txt gives C:\Ravi\file.txt ); on the contrary, it saves \\ : Join-Path C:\Ravi\\ file.txt gives C:\Ravi\\file.txt ; however, while this is not very good, it is usually benign (such paths still work to access the file system).