问题
I'm writing a script that is supposed to run two dotnet application one after the other. One on port 5000 the second one on port 5001 according to their launchSettings.json
So far this is the script that runs the applications:
$app1ProjectFolder = '../src/App1'
$app2ProjectFolder = '../src/App2'
Write-Host "STARTING APP1" -foreground Green
Push-Location $app1ProjectFolder
$dotnetRunCommandApp1 = 'run'
$app1Process = Start-Process dotnet -ArgumentList $dotnetRunCommandApp1 -PassThru
Pop-Location
Write-Host "STARTING APP2" -foreground Green
Push-Location $app2ProjectFolder
$dotnetRunCommandApp2 = 'run'
$app2Process = Start-Process dotnet -ArgumentList $dotnetRunCommandApp2 -PassThru
Pop-Location
What I need is for the script to wait for the first app to finish launching or be accessible on it's designated port before launching the second app.
回答1:
You can use:
while (!(Test-NetConnection localhost -Port 5000).TcpTestSucceeded) { Start-Sleep 1 }
To wait indefinitely for the ports to be ready.
You could add a maximum wait time e.g. say the app stayed running but failed to listen, or was firewalled.
回答2:
Start-Process has the -wait switch which should prevent the script from continuing until it's done.
$app1Process = Start-Process dotnet -ArgumentList $dotnetRunCommandApp1 -PassThru -wait
According to the Start-Process article:
Indicates that this cmdlet waits for the specified process and its descendants to complete before accepting more input. This parameter suppresses the command prompt or retains the window until the processes finish.
来源:https://stackoverflow.com/questions/56134434/powershell-wait-for-dotnet-run-to-launch-application-on-some-port