0

I got a variable that contains different strings like domainname/users/username and domainname/accounts/serviceUsers/serviceusername.

Now I want to split these strings on the last "/" so I get only the last bit (username, serviceusername).

I know how to use split when specifiying exactly on which occurance of the "/" the string should be splitted, but not generally at the last "/".

$x = 'domainname/Accounts/ServiceUsers/serviceusername' 
$x.split('/')[3]

How can I achieve that?

2 Answers 2

7

Hope this helps

$x.split('/')[-1]
Sign up to request clarification or add additional context in comments.

1 Comment

To expand on this, PowerShell allows negative subscripting to select an array element starting from the end (last element of the array). Because 0 can't be distinguished as to positive or negative (except on certain old computers), "reverse" subscripting is 1-based instead of 0-based, and the last element of $x is $x[-1], the next-to-last is $x[-2], and so on.
2

Another way. Note that -split uses regex.

'domainname/Accounts/ServiceUsers/serviceusername'-split '/' | 
  select -Last 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.