whoopn
whoopn

Reputation: 91

Powershell: Remove the last '/' character in a string with multiple paths in it from each path

I'm looking to remove the final '/' character from a string that contains multiple storage paths in it, what is the best way to go about this, I keep getting close but I still can't quite get what I'm looking for, is a loop really the only way?

$Paths = /some/path/1/ /some/path/2/ /some/path/3/
$Paths = $Paths.Remove($Paths.Length - 1)
$Index = $Paths.LastIndexOf('/')
$ID = $Paths.Substring($Index + 1)

I'm currently getting errors like the following:

Exception calling "Remove" with "1" argument(s): "Collection was of a fixed size."

The desired final version of $Paths would be

/some/path/1 /some/path/2 /some/path/3

Any help would be greatly appreciated, I think I may have a process issue as well as a coding issue...

Upvotes: 7

Views: 45355

Answers (3)

user9357295
user9357295

Reputation: 29

I was working on a function today where I needed to test the $Path switch to see if it ended with a '\' or not. This thread was helpful but I came up with another solution with a simple if statement.

The IF Statement tests the last character of the line by calculating the total length (minus 1 character) and if the last character is not equal to '\', the '\' gets added to the $Path value.

$Path = "C:\SomePath"

if ($Path.Chars($Path.Length - 1) -ne '\')
    {
        $Path = ($Path + '\')
    }

$Path Output = "C:\SomePath\"

To reverse it and remove the '\' is also a simple change using the TrimEnd() method.

$Path = "C:\SomePath\"

if ($Path.Chars($Path.Length - 1) -eq '\')
    {
        $Path = ($Path.TrimEnd('\'))
    }

$Path Output = "C:\SomePath"

Upvotes: 2

Esperento57
Esperento57

Reputation: 17492

other method, use foreach (or %) and remove last char with substring function:

$Paths = "/some/path/1/", "/some/path/2/", "/some/path/3/"
$Paths | %{$_.Substring(0, $_.length - 1) }

Upvotes: 0

tommymaynard
tommymaynard

Reputation: 2152

Use the .TrimEnd() method.

PS > $Paths = '/some/path/1/','/some/path/2/','/some/path/3/'
PS > $Paths
/some/path/1/
/some/path/2/
/some/path/3/
PS > $Paths = $Paths.TrimEnd('/')
PS > $Paths
/some/path/1
/some/path/2
/some/path/3

Upvotes: 27

Related Questions