-1

I have this variable inside PowerShell, /sites/testprojectsite/SitePages. Now how can I extract all the characters from the last / till the end, which is sitePages in my case?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
John John
  • 1
  • 72
  • 238
  • 501

3 Answers3

0

There are a lot of ways to get that.

One might be

$var = "/sites/testprojectsite/SitePages"
$leaf = $var -split "/" | Select-Object -Last 1
$leaf

Try it online.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
An-dir
  • 465
  • 2
  • 13
0

You also have the string.split() method which returns an array. With any array, an index of [-1] returns the last element:

$path = '/sites/testprojectsite/SitePages'
$path.Split('/')[-1]
PS > $path = '/sites/testprojectsite/SitePages'
PS >
PS > $path.Split('/')[-1]
SitePages
PS >
Keith Miller
  • 702
  • 5
  • 13
-1

It even works on a Mac, with PowerShell installed

Last login: Tue Mar 21 14:28:38 2023
luuk@mini ~ % pwsh
PowerShell 7.3.3
PS /Users/luuk> $x="/sites/testprojectsite/SitePages"
PS /Users/luuk> Split-Path $x -leaf
SitePages
PS /Users/luuk>
Luuk
  • 12,245
  • 5
  • 22
  • 33