Home > Software engineering >  powershell script restart services on 100s computers
powershell script restart services on 100s computers

Time:09-28

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?

CodePudding user response:

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

CodePudding user response:

Demo of invoke-command running in parallel:

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

5
  • Related