0

I need to restart the services on hundreds sometimes less depending on if backup jobs failed on the remote machine with

$services = "winmgmt", "cryptsvc", "vss"
$computers = get-content "${env:\userprofile}\servers.txt"
foreach ($srv in $ computers) {
get-service -computername $srv $services | restart-service -force
}

while this works, it does not do it asynchronously, only one at a time, is there a way I can send the job out to all the machines at once?

2
  • 3
    invoke-command comp1,comp2,comp3 runs in parallel. Commented Sep 27, 2021 at 13:33
  • @js2010 I did not know that, thanks. Commented Sep 27, 2021 at 13:51

2 Answers 2

1

You can use Invoke-Command to run the command as a Job, you can then wait for all the jobs to complete, something like this should do it.

$computers = get-content "${env:\userprofile}\servers.txt"
$sb = {
    $services = "winmgmt", "cryptsvc", "vss"
    get-service -Name $services | Restart-Service -PassThru | Get-Service
}
Invoke-Command -ComputerName $computers -ScriptBlock $sb
Sign up to request clarification or add additional context in comments.

10 Comments

Nice. Invoke-Command also accepts multiple computer names at once, so you could do Invoke-Command -ComputerName $computers -ScriptBlock $sb -AsJob |Wait-Job |Receive-Job
Even better, thanks @MathiasR.Jessen I have updated
thanks. is there a way to verify if the services were restarted?
You can use Restart-Service with Passthru and pipe it back into get-service to ensure the service is running again (Restart-Service -PassThru | Get-Service)
Invoke-Command -ComputerName $computers -ScriptBlock $sb -AsJob |Wait-Job |Receive-Job ..... what does receive-job do?
|
0

Demo of invoke-command running in parallel:

# elevated prompt
measure-command { 
  invoke-command localhost,localhost,localhost { sleep 5 } } | 
  % seconds

5

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.