powershell: remove text from end of string


–deleted earlier text – I asked the wrong question!


What I have is $var = "\\unknowntext1\alwaysSame\unknowntext2"

I need to keep only "\\unknowntext1"


Try regular expressions:

Or if you know only partially the ‘something’, then e.g.

The $1 is reference to group in parenthesis (the (some[^_]*) part).

Edit (after changed question):

If you use regex, then special characters need to be escaped:

or (another regex magic) use lookbehind like this:

(which is: take anything (.*), but there must be \\unknowntext1 before it ('(?<=\\\\unknowntext1)) and replace it with empty string.

Edit (last)

If you know that there is something known in the middle (the alwaysSame), this might help:


powershell: remove text from end of string by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply