How to get the index of the last occurence of a char in PowerShell string?

穿精又带淫゛_ 提交于 2020-12-31 04:43:45

问题


I want to get the index of the last "\" occurrence in order to trim the "Activity" word and keep it, from following string in PowerShell:

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

I'm converting the code from VBScript to PowerShell and in VB there's this solution :

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

Using Right and InStrRev functions which makes the life more easier. Unfortunately I didn't find anything like it in PowerShell. Can't find any option to scan from the end of the string.


回答1:


$String.Split("\")[-1]

Or if $String is actually a real path, you might consider:

Split-Path $String -Leaf



回答2:


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

Check out:

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



来源:https://stackoverflow.com/questions/51382576/how-to-get-the-index-of-the-last-occurence-of-a-char-in-powershell-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!