Reputation: 3109
I've got the command below:
> "D:\abc\abcName".TrimStart("D:\abc")
Name
In fact I wish this to trim exactly "D:\abc" and return only "abcName" but seems that the 2nd "abc" is trimmed off as well.
Why does this happen and how can I fix it?
I'm using PS 4.0.
Upvotes: 1
Views: 1054
Reputation: 58931
Mathias R. Jessen points it out.
Looks like you want to get the filename from a path. Instead of using TrimStart consider use the static GetFileNameWithoutExtension method:
[system.io.path]::GetFileNameWithoutExtension("D:\abc\abcName.bat")
Result:
abcName
Or if you want the complete filename with extension:
[system.io.path]::GetFileName("D:\abc\abcName.bat")
Result:
abcName.bat
Upvotes: 2
Reputation: 174515
The argument to TrimStart()
is treated as an array of char
s, not a literal string. All consecutive characters at the start of the string that match any of the characters inside the argument "D:\abc" is removed.
You could use the -replace
operator instead, which takes a regex pattern as its right-hand argument:
PS C:\> "D:\abc\abcName" -replace "^D:\\abc\\"
abcName
If you are unsure which characters to escape (such as \
), let the [regex]
class do it for you:
PS C:\> "D:\abc\abcName" -replace "^$([regex]::Escape("D:\abc\"))"
abcName
Upvotes: 2