电源外壳;从每个路径中删除其中包含多个路径的字符串中的最后一个'/'字符

时间:2017-04-24 16:06:42

标签: powershell

我想要从包含多个存储路径的字符串中删除最后的'/'字符,最好的方法是什么,我一直接近但我仍然无法得到我的东西我在寻找,这是一个循环真的唯一的方法吗?

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

我目前收到如下错误:

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

$ Paths的最终版本将是

git push

非常感谢任何帮助,我想我可能会遇到流程问题以及编码问题......

3 个答案:

答案 0 :(得分:10)

使用.TrimEnd()方法。

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

答案 1 :(得分:0)

其他方法,使用foreach(或%)并使用substring函数删除最后一个char:

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

答案 2 :(得分:0)

我今天正在研究一个函数,该函数需要测试$ Path开关以查看它是否以'\'结尾。这个线程很有帮助,但是我想出了另一个带有简单if语句的解决方案。

IF语句通过计算总长度(减去1个字符)来测试行的最后一个字符,如果最后一个字符不等于'\',则'\'将添加到$ Path值中。

$Path = "C:\SomePath"

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

$ Path Output =“ C:\ SomePath \”

使用TrimEnd()方法将其反转并删除'\'也很简单。

$Path = "C:\SomePath\"

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

$ Path Output =“ C:\ SomePath”