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 *

Recent Posts
Categories
Tags

Always On Availability Groups (AAG) (4) AWS (4) AWS Redshift (6) Certificates & Encryption (3) Change Data Capture (CDC) (2) Database Admin (72) Database Backups & Recovery (14) Database Mirroring (2) Deleting Data (1) Error Messages (5) Git Commands (6) Importing & Exporting Data (2) Linked Servers (3) Linux Admin (2) Logging & Monitoring (1) Measuring Databases (10) Microsoft Patching (2) MySQL (4) Postgres (6) PowerShell Scripts (1) SQL Server Agent (5) SQL Server Database Files (1) SQL Server Data Types (2) SQL Server Management Studio (SSMS) (15) SQL Server Network Connectivity (3) SQL Server on Linux (1) SQL Server Patching (2) SQL Server Performance (6) SQL Server Permissions (2) SQL Server Processes (SPIDs) (7) SQL Server Replication (2) SQL Server Scripts (13) Windows Admin (21) Windows Authentication (2) Windows Automation (1) Windows Events (2) Windows Firewall (4) Windows Subsystem for Linux (WSL) (18)