(对不起英语不好)我需要一个PowerShell脚本=如果下一行包含“这个字符串”,输出当前行,接下来的3行只输出当前行。例如
错误信息错误错误异常错误
如果下一行没有 'exeption' 字符串,则只输出一个 excel 文件错误,但如果错误字符串的下一行包含 exeption ,则返回错误行 + 下 3 行
(对不起英语不好)我需要一个PowerShell脚本=如果下一行包含“这个字符串”,输出当前行,接下来的3行只输出当前行。例如
错误信息错误错误异常错误
如果下一行没有 'exeption' 字符串,则只输出一个 excel 文件错误,但如果错误字符串的下一行包含 exeption ,则返回错误行 + 下 3 行
你搜索过什么?
这个用例的许多示例遍布整个网络,就在 SO 上。这里的人们很乐意提供帮助,但您必须展示努力、代码和错误。
我通常不会为这些类型的帖子这样做,但让我开始吧。因此,下次您访问时,您会更愿意帮助人们,帮助您。
只需搜索...
...并且始终阅读帮助文件,不要猜测或假设,在这种情况下,Get-Content 或 Select-String cmdlet
# Help topics
Get-Help about_*
# get function / cmdlet details
Get-help -Name Get-Content -Full
Get-help -Name Select-String -Full
...并查看 -Context 开关信息和示例。以及有关条件逻辑的帮助文件,即 if/then。
阅读讨论并查看给出的答案。
所以,你的问题几乎可以被认为是上面 SO 线程的重复,尽管它是反向的,这意味着你只需要切换方向,如第二个例子。
更新
好的,因为您刚刚发布了一些代码(尽管总是用代码更新您的问题,而不是将其放在评论部分,以便更容易理解并让人们了解),表明您走在正确的轨道上,这真的很简单:
# Example
@'
line1
line2
line3
line4
line5
'@ | Out-File -FilePath 'D:\temp\FileWithLines.txt'
Get-Content -Path 'D:\temp\FileWithLines.txt' |
Select-String -Pattern line2 -Context 0,3
<#
# Results
> line2
line3
line4
line5
#>
Get-Content -Path 'D:\temp\FileWithLines.txt' |
Select-String -Pattern line1 -Context 0,3
<#
# Results
> line1
line2
line3
line4
#>
If (Get-Content -Path 'D:\temp\FileWithLines.txt' | Select-String -Pattern line0)
{
Get-Content -Path 'D:\temp\FileWithLines.txt' |
Select-String -Pattern line1 -Context 0,3
}
Else
{
Write-Warning -Message "Current line is
$(Get-Content -Path 'D:\temp\FileWithLines.txt' |
Select-String -Pattern line1)"
}
<#
# Results
WARNING: Current line is
line1
#>
试试这样:
# get file content as an array
$lines = Get-Content "filepath"
$line = 0
# read lines one by one
$lines | foreach {
# increment line counter
$line++
if ($_ -match ".*(This string).*") {
# Line matched show current line and next 3 lines from $lines array
$_
$lines[$line..($line+3)]
}
}