【发布时间】: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