Restart a Service on Multiple Servers With PowerShell

📜Part of the PowerShell Complete Guide, every PowerShell post on this site, grouped by the job you are doing.

To restart a service on several servers at once, run Restart-Service inside Invoke-Command with a list of computer names. Each server runs the command at the same time and the results come back to your console. The example restarts the SQL Server Agent service; change the service name for anything else.

It needs PowerShell remoting (WinRM) enabled on the servers, which is the default on Windows Server, and an account that is an administrator on each of them.

Restart the Service on Several Hosts

PowerShell
# Change the host names and the service name to yours
$servers = 'SQL01', 'SQL02', 'SQL03'

Invoke-Command -ComputerName $servers -ScriptBlock {
    Restart-Service -Name 'SQLSERVERAGENT' -PassThru
} | Select-Object PSComputerName, Name, Status
Invoke-Command restarting the SQL Server Agent service on several hosts from one PowerShell window

-PassThru returns the service after the restart, so you see each server’s name and the new status in one table. Restarting SQL Server Agent stops any job that is running at that moment, so pick a quiet time. For a named SQL Server instance the Agent service is SQLAgent$INSTANCENAME, so use that name (in single quotes, because of the $).

Check First, Then Restart

Try it on one server first, and look before you change anything. The same pattern with Get-Service only reads:

PowerShell
Invoke-Command -ComputerName $servers -ScriptBlock {
    Get-Service -Name 'SQLSERVERAGENT'
} | Select-Object PSComputerName, Name, Status, StartType

In Windows PowerShell 5.1 you could also use Get-Service -ComputerName, but PowerShell 7 removed that parameter. Invoke-Command works in both. To see which one you are in, see How to Check Your PowerShell Version.

If one server fails with a WinRM or access denied error, the others still run. The error tells you which host failed, so you can deal with it on its own; to check WinRM is reachable there, test port 5985 with Test-NetConnection. If SQL Server Agent does not come back after the restart, start with SQL Server Agent Will Not Start on sqldba.blog. The services themselves are covered in SQL Server Configuration Manager.

If SQL Server is part of your day job, my current work lives over at sqldba.blog: production DBA scripts, an error library and the SSMS guide.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *