如何在PowerShell字符串中获取char的最后一次出现的索引?

Mar*_*One 1 powershell

我想获取最后一个"\"出现的索引,以便修剪"Activity"一词并保留它,从PowerShell中跟随字符串:

$string = "C:\cmb_Trops\TAX\Auto\Activity"
Run Code Online (Sandbox Code Playgroud)

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

Right(string, Len(string) - InStrRev(string, "\"))
Run Code Online (Sandbox Code Playgroud)

使用Right和InStrRev函数可以使生活更轻松.不幸的是我在PowerShell中找不到类似的东西.找不到任何从字符串末尾扫描的选项.

Kev*_*mer 7

$string = "C:\cmb_Trops\TAX\Auto\Activity"
$string = $string.Substring($string.lastIndexOf('\') + 1)
echo $string
Run Code Online (Sandbox Code Playgroud)

查看:

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


iRo*_*Ron 5

$String.Split("\")[-1]
Run Code Online (Sandbox Code Playgroud)

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

Split-Path $String -Leaf
Run Code Online (Sandbox Code Playgroud)

  • 即使它不是真正的路径,而是遵循路径语法,您也可以使用 `System.IO.Path` 类:`[IO.Path]::GetFileNameWithoutExtension($Path)`(或者,`GetFileName`) (2认同)