【问题标题】:Cannot seem to break out of Powershell Get-Content command似乎无法摆脱 Powershell Get-Content 命令
【发布时间】:2020-02-22 00:12:57
【问题描述】:

我尝试使用以下帖子中的建议;

How to stop Get-Content -wait after I find a particular line in the text file using powershell?

...但是当我按如下方式运行命令时 Get-Content 命令似乎继续(服务器名称已编辑)。 IE。当达到字符串“FATAL”时,Get-Content 继续。

Get-Content \\n------v\c$\ProgramData\Navis\center\logs\navis-apex.log -wait -Tail 1 | % {$_ ; if($_ -eq "FATAL") {break}}

【问题讨论】:

  • 您的代码的唯一具体问题可能是您将单词FATAL整行 (-eq) 匹配,而不是寻找它作为子字符串就行了,如Jawad的回答所示。但是,您从链接帖子中引用的代码有一个重要缺陷:break 并非旨在退出 管道:在没有封闭 loop 的情况下,它 退出整个脚本 - 请参阅 Jawad 的回答和 this one 了解更多背景信息。
  • 感谢大家的回复,似乎已经解决了这个问题。 :)

标签: powershell


【解决方案1】:

如果你是逐行阅读,你不能检查整行和一个单词。

Get-Content \\n----v\c$\ProgramData\Navis\center\logs\navis-apex.log -wait -Tail 1 |
  % {$_ ; if($_ -match "FATAL") {break}}

您想检查内容并查看它是否包含单词,请使用-match-like 运算符。

注意事项和解决方法

我想补充一点,如果您在此之后有代码,它将不会被执行。正如@mklement0 指出的那样,没有在管道周围使用带有虚拟循环的 break,目前无法提前退出管道

Get-Content C:\temp\file.txt -wait -Tail 1 | % { if ($_ -match "EXIT") {"found the match"; break;} }
Write-Output "Printing Next Statement" # Will not execute.. script exited already.

#outputs
found the match

解决方法 1: 使用 throw 语句尝试/捕获。

try {
    Get-Content C:\temp\file.txt -wait -Tail 1 | % { if ($_ -match "EXIT") {"found the match"; throw "Exiting loop";} }
}
catch {
    Write-Output "All Contents Retreived."
}

Write-Output "Printing Next Statement"

#Outputs
found the match
All Contents Retreived.
Printing Next Statement

解决方法 2 使用虚拟循环。

while ($true) {
    Get-Content C:\temp\file.txt -wait -Tail 1 | % { if ($_ -match "EXIT") {"found the match"; break;} }
}
Write-Output "Printing Next Statement"

#outputs
found the match
Printing Next Statement

【讨论】:

    【解决方案2】:

    这对我很有效:

    Get-Content "\\path_to\log.log" -wait -Tail 1 | % {   
            if($_ -match "FATAL")
            {   write-warning $_
                break
            }
            else
            {   write-host $_
            }
        }
    

    【讨论】:

    • break 并非旨在退出 管道:在没有封闭 循环 的情况下,它会作为一个整体退出脚本;目前没有直接方法可以提前退出管道,尽管添加这样的功能是long-standing proposal 的主题。 A - limited - 解决方法是在管道周围使用 虚拟循环;见this answer
    猜你喜欢
    • 1970-01-01
    • 2018-01-14
    • 1970-01-01
    • 2011-12-16
    • 2018-12-14
    • 2021-02-12
    • 2012-08-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多