8

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.

Marked One
  • 294
  • 2
  • 3
  • 13
  • 2
    PowerShell is .NET based, and `String` has `LastIndexOf`, so `.LastIndexOf('\')` would do. But what you're probably *really* after is `Split-Path` (and the other cmdlets PowerShell has for path parsing). – Jeroen Mostert Jul 17 '18 at 13:30
  • 2
    Possible duplicate of [Split a string with powershell to get the first and last element](https://stackoverflow.com/questions/32095674/split-a-string-with-powershell-to-get-the-first-and-last-element) – iRon Jul 17 '18 at 14:04

2 Answers2

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

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

Split-Path $String -Leaf
iRon
  • 20,463
  • 10
  • 53
  • 79
  • 2
    Even if it's not a real path, but follows a path syntax, you could use the `System.IO.Path` class: `[IO.Path]::GetFileNameWithoutExtension($Path)` (alternatively, `GetFileName`) – Maximilian Burszley Jul 17 '18 at 14:45
7
$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

Kevin Cranmer
  • 135
  • 2
  • 11
  • I'm sorry but I think I wasn't precise at what I wrote. I want the opposite. Keep only the "Activity" and eliminate everything else. – Marked One Jul 17 '18 at 13:53
  • `$string = $string.Substring($string.lastIndexOf('\') + 1)` Sorry, you were clear; I just misread :) – Kevin Cranmer Jul 17 '18 at 14:12
  • 1
    @CrazyCranberry I suggest you edit your answewr to contain the corrected version - so follow up readers don't have to sieve through comments. –  Jul 17 '18 at 14:54