2016-06-07 93 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

太棒了,謝謝你的幫助! –