【问题标题】:Powershell: Remove the last '/' character in a string with multiple paths in it from each pathPowershell:从每个路径中删除包含多个路径的字符串中的最后一个“/”字符
【发布时间】:2017-09-21 10:05:05
【问题描述】:

我希望从包含多个存储路径的字符串中删除最后一个“/”字符,最好的方法是什么,我一直在接近,但我仍然无法完全理解我想要的正在寻找,循环真的是唯一的方法吗?

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

我目前遇到如下错误:

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

所需的 $Paths 最终版本是

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

任何帮助将不胜感激,我想我可能有流程问题以及编码问题...

【问题讨论】:

标签: powershell


【解决方案1】:

使用 .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

【讨论】:

    【解决方案2】:

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

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

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

    $Path 输出 = "C:\SomePath\"

    使用 TrimEnd() 方法来反转它并删除 '\' 也是一个简单的更改。

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

    $Path 输出 = "C:\SomePath"

    【讨论】:

      【解决方案3】:

      其他方法,使用 foreach(或 %)并使用子字符串函数删除最后一个字符:

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

      【讨论】:

      • 但是如果你有一个像"some/path" 这样的路径由于某种原因它切断了"h" 并且路径变得不正确怎么办?如果最后一个字符是斜线,您应该检查,或者使用@tommymaynard 的解决方案
      • 虽然欢迎使用此代码 sn-p,并且可能会提供一些帮助,但它会是 greatly improved if it included an explanation of 如何解决这个问题。没有这个,你的回答就没有多少教育价值了——记住你是在为未来的读者回答这个问题,而不仅仅是现在提问的人!请edit您的答案添加解释,并说明适用的限制和假设。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 2019-03-04
      • 1970-01-01
      相关资源
      最近更新 更多