PowerShell 实现 grep 的效果


PowerShell 在输出的时候会根据《ETS扩展类型系统》对对象进行格式化,而直接使用Select-String(sls)命令会先调用对象的ToString()方法再匹配,导致无法直接筛选出显示在屏幕上的内容:

PS C:\test> alias

CommandType     Name
-----------     ----
Alias           % -> ForEach-Object
Alias           ? -> Where-Object
Alias           ac -> Add-Content
Alias           cat -> Get-Content
...

PS C:\test> alias | sls cat

cat

PS C:\test> alias | sls Object
PS C:\test>(空)

解决办法来自于:https://stackoverflow.com/questions/1485215/powershell-how-to-grep-command-output

先使用Out-String -stream,再用sls即可:

PS C:\test> alias | Out-String -stream | sls Object

Alias           % -> ForEach-Object
Alias           ? -> Where-Object
Alias           compare -> Compare-Object
Alias           diff -> Compare-Object
Alias           foreach -> ForEach-Object
Alias           group -> Group-Object
Alias           measure -> Measure-Object
Alias           select -> Select-Object
Alias           sort -> Sort-Object
Alias           tee -> Tee-Object
Alias           where -> Where-Object

另外注意sls使用的是正则pattern,必要的地方需要转义。

×用微信扫描并分享
本文链接: https://www.pstips.net/powershell-%e5%ae%9e%e7%8e%b0-grep-%e7%9a%84%e6%95%88%e6%9e%9c.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

发表评论

电子邮件地址不会被公开。 必填项已用*标注