Powershell 读取文件中的文本等待找到然后继续

Kaz*_*zic 3 powershell

我正在开发一个跨远程服务器启动某些服务的过程,但是服务器 2 无法启动,直到在服务器 1 日志中找到消息,服务器 3 才能启动,直到服务器 2 中找到相同的消息,等等。

我的问题是,是否可以在“循环”中读取文件,并且在找到该消息之前不继续进行初始循环(然后继续前进)?我想我可以在下面做,但是,虽然它确实识别出日志文件中的字符串已找到,但它只是重复找到它,直到内置计时器完成然后向前移动。因此,该过程将类似于“读取此文件,如果找到字符串,则继续前进。如果未找到字符串,则等待 30 秒并重新扫描文件。如果找到,则继续前进,如果未找到,则再等待 30 秒,然后重新扫描(我可以连续重复)< 执行此操作,直到找到字符串。示​​例:在此处输入图像描述

任何建议将不胜感激,因为我认为我可能会从错误的角度来处理这个问题......

-- 我省略了此脚本之前的大部分脚本,只包含 If/Else 语句,因为这是它检查文件的地方。

$SEL = Select-String -Path \\$Server\$RootDir\folder\anotherfolder\A-Log-File.log -Pattern "Switching to status: STARTED"
if ($SEL -ne $null)
{
    Write-Host "FOUND: Switching to status: STARTED" -ForegroundColor Yellow -BackgroundColor DarkGreen
}
else
    {
        Write-Host **** Waiting 60 seconds for cache to build ****
            [int]$Time = 60
            $Lenght = $Time / 100
            For ($Time; $Time -gt 0; $Time--) {
            $min = [int](([string]($Time/60)).split('.')[0])
            $text = " " + $min + " minutes " + ($Time % 60) + " seconds left"
            Write-Progress -Activity "Waiting for Started Message" -Status $Text -PercentComplete ($Time / $Lenght)
            Start-Sleep 1
        $SEL = Select-String -Path \\$Server\$RootDir\folder\anotherfolder\A-Log-File.log -Pattern "Switching to status: STARTED"
        if ($SEL -ne $null)
        {
            Write-Host "FOUND: Switching to status: STARTED" -ForegroundColor Yellow -BackgroundColor DarkGreen
        }
        else
            {
                Write-Host **** A-Log-File.log Log does NOT contain a started message **** -ForegroundColor Red -BackgroundColor Yellow 
                Write-Host **** Investigate further or increase the int-time time on Line 54 to 180 seconds **** -ForegroundColor Red -BackgroundColor Yellow ##This part goes away once action can be taken based on reading contents of the file
            }
                                                }
    }
Run Code Online (Sandbox Code Playgroud)

Mat*_*sen 5

您不需要循环,只需使用Get-Content -Wait

$null = Get-Content "\\$Server\$RootDir\folder\anotherfolder\A-Log-File.log" -Wait |Where-Object { $_ -match 'Switching to status: STARTED' } |Select -First 1
Run Code Online (Sandbox Code Playgroud)

Get-Content -Wait将继续输出写入文件的新行,直到它被中断 - 幸运的是,Select -First 1一旦我们观察到字符串,我们就可以用来停止管道

  • @marsze `Select -First 1` 将[停止管道](/sf/ask/4255319141/#60791320)一旦找到字符串:) (3认同)