Restart Services on Multiple Hosts using PowerShell

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 good 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 PowerShell cmdlet.

Restarting SQL Agent Service using PowerShell

Before running the script below, change the ComputerName param to include your hostnames:

# Restart service on multiple hosts
$parameters = @{
  ComputerName = 
  	"Hostname1",
  	"Hostname2",
  	"Hostname3"
  ScriptBlock = { Restart-Service *SQLSERVERAGENT* }
}
Invoke-Command @parameters
PowerShell Restart-Service cmdlet example

The ScriptBlock argument can be amended to run any command you like. You can add error checking if you’re building something that needs that enhanced reliability.

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.


Comments

Leave a Reply

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