2

If I have a path that is unpredictable but I always want the LAST part after the final backslash, how should I approach this?

For example

\\intra.X.net\Exploitation\X\Poste\Travail\X\X\folder\test

I want to output test only.

C:\temp\a\b\CDE\FG\HI

I want to output HI only.

I'm thinking counting how many backslashes then using splits, but do you have a better way to suggest?

Rakha
  • 1,874
  • 3
  • 26
  • 60
  • 3
    `$String.split('\')[-1]` or `split-path -leaf "\\intra.X.net\Exploitation\X\Poste\Travail\X\X\folder\test"` –  Nov 13 '18 at 13:23
  • Possible duplicate of [Extract the filename from a path](https://stackoverflow.com/questions/35813186/extract-the-filename-from-a-path) –  Nov 13 '18 at 13:30
  • @LotPings thanks a lot my friend! I managed to get the Split-path working in an expression within a pipeline : | Select-Object Name, @{name='Folder';expression={ Split-Path $($_.Directory) -leaf } } How would I write the split using $_.Directory though? Can't get it to work. – Rakha Nov 13 '18 at 13:36
  • Depending on the type, you might have to cast to a [string] first. Or try `$_.Parent.Name` –  Nov 13 '18 at 13:55
  • Use `$_.DirectoryName` – marsze Nov 13 '18 at 14:02
  • @Rakha - the `.Directory` property IS ALREADY just the last dir of the path to the object. [*grin*] no need to split anything ... – Lee_Dailey Nov 13 '18 at 14:22
  • Yes, if you use ().Directory you get only the names, but when you select, directory is the full path. get-childitem C:\temp -recurse | select name,directory z.txt C:\temp dsdfsf.txt C:\temp\zzz – Rakha Nov 13 '18 at 15:11

1 Answers1

1

As pointed out in the comments,

You can call .split('\')[-1] like this:

$path = "\\intra.X.net\Exploitation\X\Poste\Travail\X\X\folder\test"
$last = $path.split('\')[-1] # test

Or you can call split-path with the leaf arg like this:

$path = "C:\temp\a\b\CDE\FG\HI"
$last = split-path $path -leaf # HI
KyleMit
  • 30,350
  • 66
  • 462
  • 664