简体   繁体   English

从Powershell中的外部命令输出中提取模式

[英]Extracting a pattern from output of an external command in Powershell

For my powershell script, I run an external command and look for a specific pattern in the output. 对于我的powershell脚本,我运行一个外部命令并在输出中查找特定的模式。 For example: 例如:

The command "eraseDevice" gives me output like this: 命令“ eraseDevice”给我这样的输出:

Erasing Deployment... Erasing sector 0x080a8000 
Erasing sector 0x080c1000 
Erasing sector 0x080e1000 
Erasing sector 0x64010000 
Rebooting... 

I want the number 0x080a8000 from this output. 我希望此输出中的数字为0x080a8000。 I have tried the following: 我尝试了以下方法:

eraseDevice | select-string -simplematch -pattern 0x 

which returns the lines that contain the hexadecimal number. 返回包含十六进制数字的行。 I tried doing the following as well, but all of them return errors: 我也尝试执行以下操作,但是所有这些都返回错误:

eraseDevice | select-string -simplematch -pattern 0x -totalcount 1 
eraseDevice | (select-string -simplematch -pattern 0x)[4] 
eraseDevice | (select-string -simplematch -pattern 0x).split()[4] 

Desired output: 0x080a8000 from the first line. 所需的输出:第一行的0x080a8000。 Thanks for your help. 谢谢你的帮助。

You can use Select-Object to get only the first line of output from eraseDevice : 您可以使用Select-Object来仅获取eraseDevice的第一行输出:

eraseDevice | Select-Object -First 1;

Then pipe that into Select-String to find '0x' followed by exactly eight hexadecimal characters: 然后,将其通过管道传递到Select-String以查找'0x'后跟正好是八个十六进制字符:

eraseDevice | Select-Object -First 1 | Select-String -Pattern '0x[0-9a-f]{8}'

Select-String returns instances of the MatchInfo class . Select-String返回MatchInfo类的实例。 To retrieve just the matched number, access the Value property of the first element of the Matches collection: 要仅检索匹配的数字,请访问Matches集合的第一个元素的Value属性:

eraseDevice `
    | Select-Object -First 1 `
    | Select-String -Pattern '0x[0-9a-f]{8}' `
    | ForEach-Object { $_.Matches[0].Value };

Note that if you did want to extract the sector number from all lines of output, you could just remove Select-Object from the pipeline and leave the rest of the command unmodified. 请注意,如果您确实想从输出的所有行中提取扇区号,则只需从管道中删除Select-Object ,然后保留其余命令不变。

$r = [regex] "(0x[0-9a-f]+)"
$line = (eraseDevice | select -first 1)
$num = $r.match($line).groups[1].value

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM