Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 554
Ravichandra Avatar asked May 09 '16 11:05

Ravichandra


People also ask

How do I trim a string at the end of PowerShell?

To trim whitespace from strings, simply call the trim() method with no arguments like below. When the PowerShell Trim () method is not supplied with any parameters then the Char. IsWhiteSpace method is called and all leading and ending whitespace characters found are removed.

What does split path do in PowerShell?

The Split-Path cmdlet returns only the specified part of a path, such as the parent folder, a subfolder, or a file name. It can also get items that are referenced by the split path and tell whether the path is relative or absolute. You can use this cmdlet to get or submit only a selected part of a path.

How do I extract part of a string in PowerShell?

When you want to extract a part of a string in PowerShell we can use the Substring() method. This method allows us to specify the start and length of the substring that we want to extract from a string.


2 Answers

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

"C:\Ravi\".TrimEnd('\')
like image 173
Martin Brandl Avatar answered Oct 05 '22 22:10

Martin Brandl


no need to overcomplicate

"C:\Ravi\".trim('\')
like image 28
Loïc MICHEL Avatar answered Oct 05 '22 20:10

Loïc MICHEL