Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

powershell

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.

like image 306
Marked One Avatar asked Jul 17 '18 13:07

Marked One


People also ask

How do you find the last index of a character in a string?

The lastIndexOf() method returns the index (position) of the last occurrence of a specified value in a string. The lastIndexOf() method searches the string from the end to the beginning. The lastIndexOf() method returns the index from the beginning (position 0).

How do I get the last character of a string in PowerShell?

Use the Substring() method, specifying the following two parameters: The starting position, which should be the length of the string minus the number of characters you're after. If you want the last 4 characters in the string then use the length minus 4. The number of characters you want returned.

How do you find the last occurrence of a string?

strrchr() — Locate Last Occurrence of Character in String The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string .

How do you check if a string contains a Substring in PowerShell?

If you want to know in PowerShell if a string contains a particular string or word then you will need to use the -like operator or the . contains() function. The contains operator can only be used on objects or arrays just like its syntactic counterpart -in and -notin .


2 Answers

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

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

Split-Path $String -Leaf
like image 159
iRon Avatar answered Nov 15 '22 09:11

iRon


$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

like image 43
CrazyCranberry Avatar answered Nov 15 '22 10:11

CrazyCranberry