'Is there a PowerShell command to tell PS not to wait for a service to start before continuing?

Powershell is waiting for a service to start or stop before it moves on to the next line in the script, but I need it to move on without waiting.

The idea behind this is that we need to start and stop multiple services on multiple servers and if we wait for each service to start in succession, it could take hours for the full script to run.

Everything I have seen online is that PowerShell needs a command to tell it to wait, but my experience is that PS will wait for the service without receiving any explicit command.

Write-host "Starting services..."

## Remote Start XXX services
   Write-Host "Starting XXX services..."
   Get-Service -Name ServiceXXX -ComputerName computerXXX | Start-service
   Get-Service -Name ServiceXXX -ComputerName computerYYY | Start-service
   Get-Service -Name ServiceXXX -ComputerName computerZZZ | Start-service

## Remote Start YYY services
   Write-Host "Starting YYY services..."
   Get-Service -Name ServiceYYY -ComputerName computerAAA | Start-service
   Get-Service -Name ServiceYYY -ComputerName computerBBB | Start-service
   Get-Service -Name ServiceYYY -ComputerName computerCCC | Start-service

Ideally, I want the code to run so that ServiceXXX on computerYYY is not waiting for ServiceXXX on computerXXX, and so on for each service.

Within the script I have options to start, stop, and check. We are not worried about the system checking before it continues.

Right now, PS will run "Waiting for ServiceXXX to start..." and will repeat that message for about 30 or 40 seconds. Then it moves on to the next line. You can see why this would take a very long time once we start talking about tens of remote servers and tens of services on each one.



Solution 1:[1]

Use powershell jobs to run tasks in the background. When you've kicked them all off, you can then wait for them to complete. Something like this:

$jobs = @()
Write-host "Starting services..."

## Remote Start XXX services
   Write-Host "Starting XXX services..."
   $jobs += Start-Job {Get-Service -Name ServiceXXX -ComputerName computerXXX | Start-service}
   $jobs += Start-Job {Get-Service -Name ServiceXXX -ComputerName computerYYY | Start-service}
   $jobs += Start-Job {Get-Service -Name ServiceXXX -ComputerName computerZZZ | Start-service}

## Remote Start YYY services
   Write-Host "Starting YYY services..."
   $jobs += Start-Job {Get-Service -Name ServiceYYY -ComputerName computerAAA | Start-service}
   $jobs += Start-Job {Get-Service -Name ServiceYYY -ComputerName computerBBB | Start-service}
   $jobs += Start-Job {Get-Service -Name ServiceYYY -ComputerName computerCCC | Start-service}

#Now wait for all of them to complete
Wait-Job $jobs

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sven Mawby