在PowerShell中等待命令输出的文本

3

如何将以下bash语句翻译为PowerShell?

( docker-compose -f docker-compose.yml logs -f & ) | grep -q "Initialization Complete"

该语句会跟踪 docker 日志,直到找到文本 "Initialization Complete",然后允许脚本继续执行。 我已经做到了这一点,但不确定如何在找到文本后继续执行脚本。
docker-compose -f docker-compose.yml logs -f | Out-String -Stream | Select-String "Initialization Complete"
1个回答

3

通常情况下,PowerShell 的 tail -f 等效命令是 Get-Content -Wait

然而,你聪明地将 Bash 子 shell ((...)) 与后台进程 (&) 结合起来的方法在 PowerShell 中没有直接等效命令。

相反,你需要使用一个循环来监视 PowerShell 中的后台进程:

# Start the Docker command as a background job.
$jb = Start-Job { docker-compose -f docker-compose.yml logs -f }

# Loop until the data of interest is found.
while ($jb.HasMoreData) { 
  # Receive new data output by the background command, if any,
  # and break out of the loop once the string of interest is found.
  Receive-Job $jb -OutVariable output | 
    ForEach-Object { if ($_ -match "Initialization Complete") { break } }
  # With a stream that is kept open, $jb.HasMoreData keeps reporting $true.
  # To avoid a tight loop, we sleep a little whenever nothing was received.
  if ($null -eq $output) { Start-Sleep -Seconds 1 } 
}

# Clean up the background job, if it has completed.
if ($jb.Status -eq 'Complete') { Remove-Job $jb }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接