0

I have a string

Projects\TestEnvironment\11111xx\1111111

and need to get 1111111 from it. What I'm doing now is:

$name = $dir.Substring($dir.IndexOf('\')+1)

where $dir is my string, however it only removes up to first string, is it possible to change direction?

1
  • 1
    Just another one : $name = $dir -replace '^.*\\','' Commented Mar 17, 2017 at 17:29

3 Answers 3

6

What about using split-path?

$string = 'Projects\TestEnvironment\11111xx\1111111'
Split-Path $string -Leaf

returns 1111111.

Note the -Leaf parameter indicates that this cmdlet returns only the last item or container in the path.

Sign up to request clarification or add additional context in comments.

1 Comment

This would also work. [io.path]::GetFileName("Projects\TestEnvironment\11111xx\1111111")
3

@Robin's answer is good if the string is always a path (separated with "\"); in the general case, where the delimiter may be a different character, you can use

$string = "This-is-a-string-with-delimiters"
$lastword = ($string -split "-")[-1]

The -split operator defaults to splitting on a space, but will split on any character you choose to pass it, returning an array of strings, each string being the material before/between/after delimiters - in the example above, each word would be in a separate string in the array. Negative subscripts to an array count from the end of the array rather than the start, and are 1-origin rather than 0-origin - so $x[-1] is the last element of the array $x.

This technique also works on paths;

$path = "C:\Users\JSmith\Documents\Resume.doc"
$filename = ($path -split "\\")[-1]

will give you $filename -eq Resume.doc. Note that the delimiter passed to -split in this case is escaped, because the delimiter can be a regular expression, and the backslash ("\") is meaningful in regular expressions (it's the character that indicates that another meaningful character is to be "escaped", or its meaning ignored).

2 Comments

These appear to be for directory paths so the delimeter probably is not going to be in question in this case. Note that split supports regex so your last example would fail.
@Matt - Good catch; I'd forgotten that -split supports regular expressions. Fixed/updated.
0

other solution

('Projects\TestEnvironment\11111xx\1111111' -split '\\')[-1]

or

'Projects\TestEnvironment\11111xx\1111111'.Split('\')[-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.