Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for text in command output in powershell

How do I translate the following bash statement to PowerShell?

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

The statement tails the docker logs until it finds the text "Initialization Complete", then allows the script to proceed.

I've gotten this far but am not sure how to continue script execution after the text is found.

docker-compose -f docker-compose.yml logs -f | Out-String -Stream | Select-String "Initialization Complete"
like image 871
Carolyn Van Slyck Avatar asked Jun 09 '26 20:06

Carolyn Van Slyck


1 Answers

Generally, PowerShell's tail -f equivalent is Get-Content -Wait.

However, your clever combination of a Bash subshell ((...)) with a background process (&) has no direct PowerShell equivalent.

Instead, you must employ a loop to monitor the background process in 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 }
like image 86
mklement0 Avatar answered Jun 11 '26 12:06

mklement0