gpt4 book ai didi

bash - 在 powershell 中等待命令输出中的文本

转载 作者:行者123 更新时间:2023-11-29 09:29:45 25 4
gpt4 key购买 nike

如何将以下 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"

最佳答案

通常,PowerShell 的 tail -f 等效于 Get-Content -Wait

但是,Bash 子外壳 ((...)) 与后台进程 (&) 的巧妙组合没有直接的 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 }

关于bash - 在 powershell 中等待命令输出中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37684282/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com