【问题标题】:Search a text file for a string and output its context in Powershell?在文本文件中搜索字符串并在 Powershell 中输出其上下文?
【发布时间】:2018-06-18 17:08:10
【问题描述】:

我正在尝试在文本文件中搜索特定字符串并输出该行及其上下文:

$StateCheck = Select-String -Path C:\ImageManagerTool\Results.txt -Pattern "State:*"
$SValueCheck = Select-String -Path C:\ImageManagerTool\Results.txt -Pattern "State Value:*"

If(Get-Content C:\ImageManagerTool\Results.txt | %{$StateCheck -notmatch "State: Active"})
{
    Get-Content C:\ImageManagerTool\Results.txt | Select-String -Pattern "State:*"-Context 2,7| Select-String -Pattern "State: Active" -NotMatch |Select-String -Pattern "State Value:*" -NotMatch
} 

If(Get-Content C:\ImageManagerTool\Results.txt | %{$SValueCheck -notmatch "State Value: 0"})
{
    Get-Content C:\ImageManagerTool\Results.txt | Select-String -Pattern "State Value:*"-Context 3,6| Select-String -Pattern "State Value: 0" -NotMatch
}

以上脚本的结果:

到目前为止,我所能完成的只是输出我想要查找的字符串实例,而不是它们的上下文。使用“if”语句的当前设置来过滤不匹配的字符串的数据,我还没有弄清楚使用参数 -context 是否可以在这种情况下工作,因为 -context 在接收 Select- 时无效字符串命令。在 PowerShell 站点上阅读 Microsoft 对 -Context 的描述时,它指出上下文作为字符串数组存储在对象的上下文属性中。有没有办法可以重写我的脚本片段以获得所需的效果(即开关?)或利用上下文参数作为属性来输出其数据?

【问题讨论】:

  • 不是多次读取文件C:\ImageManagerTool\Results.txt,而是将其存储在一个变量中并对其进行操作。也通过editing你的问题显示内容。

标签: powershell


【解决方案1】:

您的 if 语句完全没有必要 - 如果没有与您提供的模式匹配,Select-String 将不会返回任何内容。

对于第二个正则表达式匹配,您可以使用Where-Object 检查匹配的行,而不是链接Select-String

Select-String -Path C:\ImageManagerTool\Results.txt -Pattern "State:*"-Context 2,7|Where-Object {$_.Line -notmatch "State: Active" -and $_.Line -notmatch "State Value:*"}

第二个示例可以进一步简化,只需确保 State Value: 之后的内容不是 0 - 您可以使用类似 [^0] 的否定字符集:

Select-String -Path C:\ImageManagerTool\Results.txt -Pattern "State Value: [^0]" -Context 3,6

【讨论】:

  • 'State Value' 行很好用,但 'State' 行只显示数据片段,在同一个脚本中运行这两行将分别运行它们的每个查询彼此(即输出将显示第 308 行,然后跳转到第 183 行并从那里开始)。在“状态”的情况下,上下文是否在 Where-Object 的搜索范围内?
猜你喜欢
  • 2015-10-15
  • 2011-09-03
  • 2013-09-27
  • 1970-01-01
  • 1970-01-01
  • 2023-02-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多