Menu & Search

PowerShell Restart Services on Multiple Hosts

PowerShell Restart Services on Multiple Hosts

In this post, we’ll walk through a script that restarts services on multiple remote hosts using PowerShell. A single PowerShell command will be run on several computers at the same time.

If you need to run a command on multiple remote machines, the PowerShell Invoke-Command cmdlet is a great option. We use this to send commands for execution on remote computers.

The command being passed in this demo is restarting the SQL Server Agent Service using the Restart-Service.

Restart Services Multiple Hosts with PowerShell

To use the script, simply populate the ComputerName array with your hostnames and then run the script. Here’s an example:

# Restart service on multiple hosts
$parameters = @{
  ComputerName = 
  ScriptBlock = { Restart-Service *SQLSERVERAGENT* }
Invoke-Command @parameters
PowerShell Restart-Service

The ScriptBlock argument can be amended to run a different PowerShell command, or you can add error checking if you’re building something more complex.

Remember that you should always be careful when running scripts that modify services on remote hosts. It’s a good idea to test the script on a single host before running it on multiple hosts to ensure that it works as expected.

As always, hope to follow this up with more of the same random blog posts. Feel free to check out my other PowerShell Tips.