Powershell command to trim path if it ends with "\"

Ravichandra picture Ravichandra · May 9, 2016 · Viewed 12.1k times · Source

I need to trim path if it ends with \.

C:\Ravi\

I need to change to

C:\Ravi

I have a case where path will not end with \ (Then it must skip).

I tried with .EndsWith("\"), but it fails when I have \\ instead of \.

Can this be done in PowerShell without resorting to conditionals?

Answer

Martin Brandl picture Martin Brandl · May 9, 2016

Consider using TrimEnd instead (especially if you are working with UNC Path):

"C:\Ravi\".TrimEnd('\')