[英]Using PowerShell Split & regex to return everything after a regex match
Going through PowerShell logs, I'm attempting to extract the commands while discarding the path the command was ran from.通过 PowerShell 日志,我试图提取命令,同时丢弃命令运行的路径。 For example,
例如,
PS C:\Windows\system32> pwd
I'd only like to return pwd
.我只想返回
pwd
。 I know this can be accomplished with .split
, but I'm struggling to get the regex working.我知道这可以用
.split
来完成,但我正在努力让正则表达式工作。 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)).*(?=(> ))
.我现在的尝试是匹配“PS”和“>”之间的字符串,例如这里的正则表达式
(?<=(PS)).*(?=(> ))
。 However this causes unintended results when the path has the letters 'ps' in it.但是,当路径中包含字母“ps”时,这会导致意外结果。
Splitting off of >
is not wanted either, since if a command has >
in it then I don't want to trim the actual command.拆分
>
也不想要,因为如果命令中有>
那么我不想修剪实际命令。
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 ">"编辑:如评论中所述更改正则表达式 - “>”不需要 escaping
Are you wanting to use RegEx to do the extracting of the command?您要使用 RegEx 提取命令吗?
Try this:尝试这个:
$Line = 'PS C:\Windows\system32> pwd'
if($Line -match '(?i)ps [a-z]:(?:\\[a-z0-9]+)+>(?<Cmd>.*)') {
$Matches.Cmd
}
Returns pwd
.返回
pwd
。 Place a space between >(
to remove the leading space.在
>(
之间放置一个空格以删除前导空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.