【问题标题】:How to get the index of the last occurence of a char in PowerShell string?如何获取 PowerShell 字符串中最后一次出现的字符的索引?
【发布时间】:2018-07-17 23:17:02
【问题描述】:

我想从 PowerShell 中的以下字符串中获取最后一个“\”出现的索引,以便修剪“活动”字并保留它:

$string = "C:\cmb_Trops\TAX\Auto\Activity"

我正在将代码从 VBScript 转换为 PowerShell,在 VB 中有这个解决方案:

Right(string, Len(string) - InStrRev(string, "\"))

使用 Right 和 InStrRev 函数让生活更轻松。不幸的是,我在 PowerShell 中没有找到类似的东西。找不到从字符串末尾开始扫描的任何选项。

【问题讨论】:

标签: powershell


【解决方案1】:
$String.Split("\")[-1]

或者如果$String实际上是一条真实的路径,你可以考虑:

Split-Path $String -Leaf

【讨论】:

  • 即使它不是真正的路径,但遵循路径语法,您也可以使用 System.IO.Path 类:[IO.Path]::GetFileNameWithoutExtension($Path)(或者,GetFileName
【解决方案2】:
$string = "C:\cmb_Trops\TAX\Auto\Activity"
$string = $string.Substring($string.lastIndexOf('\') + 1)
echo $string

退房:

https://community.spiceworks.com/topic/1330191-powershell-remove-all-text-after-last-instance-of

【讨论】:

  • 很抱歉,我认为我写的内容并不准确。我想要相反的。只保留“活动”并消除其他所有内容。
  • $string = $string.Substring($string.lastIndexOf('\') + 1) 对不起,你说的很清楚;我只是看错了:)
  • @CrazyCranberry 我建议您编辑您的答案以包含更正的版本 - 因此后续读者不必筛选 cmets。
猜你喜欢
  • 2012-02-22
  • 2019-05-28
  • 1970-01-01
  • 2012-03-23
  • 2021-08-22
  • 1970-01-01
  • 1970-01-01
  • 2021-01-10
  • 1970-01-01
相关资源
最近更新 更多