等待 powershell 中命令输出中的文本



如何将以下 bash 语句转换为 PowerShell?

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

该语句尾随 docker 日志,直到找到文本"初始化完成",然后允许脚本继续。

我已经走到了这一步,但不确定在找到文本后如何继续执行脚本。

docker-compose -f docker-compose.yml logs -f | Out-String -Stream | Select-String "Initialization Complete"

一般来说,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 }

相关内容

  • 没有找到相关文章

最新更新