2016-06-07 53 views
2

如何将以下bash语句转换为PowerShell?在PowerShell中等待命令输出中的文本

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

该声明拖尾码头日志,直到它找到文本“初始化完成”,然后允许脚本继续。

我已经得到了这么多,但我不知道如何在找到文本后继续脚本执行。

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

回答

1

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

这让我对那里的方式99%。唯一的问题是脚本不能在找到文本后继续执行,因为“docker compose logs -f”仍在运行。 –

+0

@CarolynVanSlyck:我明白了;我已经完全重写了答案。 – mklement0

+1

太棒了,谢谢你的帮助! –