Home > OS >  Using PowerShell Split & regex to return everything after a regex match
Using PowerShell Split & regex to return everything after a regex match

Time:03-17

Going through PowerShell logs, I'm attempting to extract the commands while discarding the path the command was ran from. For example,

PS C:\Windows\system32> pwd

I'd only like to return pwd. I know this can be accomplished with .split, but I'm struggling to get the regex working. The path will vary, so building a regex off a specific path will not work. My attempt right now is to match the string between "PS" and "> ", such as the regex here (?<=(PS)).*(?=(> )). However this causes unintended results when the path has the letters 'ps' in it.

Splitting off of > is not wanted either, since if a command has > in it then I don't want to trim the actual command.

CodePudding user response:

Simply take the line, split it and take the last - no regex required if you want it that way

(("PS C:\Windows\system32> pwd") -split "> ",2)[-1]

Not the best regex, but will do the job:

("PS C:\Windows\system32> pwd") -replace "^.*?> ",""

Edit: changed regex as mentioned in comment - escaping unnecessary for ">"

CodePudding user response:

Are you wanting to use RegEx to do the extracting of the command?

Try this:

$Line = 'PS C:\Windows\system32> pwd'
if($Line -match '(?i)ps [a-z]:(?:\\[a-z0-9] ) >(?<Cmd>.*)') {
    $Matches.Cmd
}

Returns pwd. Place a space between >( to remove the leading space.

  • Related