Blog

Restart Service on Remote Computer with PowerShell

If you search for "PowerShell Restart Service Remote Computer", the challenge is a lot of the top results will be for earlier versions of PowerShell and a lot more complicated than needed.  For some reason, Microsoft doesn't just give the Restart-Service command a -ComputerName switch...I guess that would be too intuitive.   After some digging, I found it's still easy, you just need to Get-Service first.  Below is an example of restarting BITS.  I used a wildcard just to show you that wildcards work.  Run this from an elevated PowerShell prompt and replace <COMPUTERNAME> with the name of your computers.

Get-Service -Name BIT* -ComputerName <COMPUTERNAME> | Restart-Service

This works great for restarting a service on a few remote computers.  If you need to restart a service for all the computers in your domain, here's a script to help with that process.  This script does need to be run from an AD server as it requires Get-ADComputer or you'll need to install the PS module on the server where you'll be running this script.   The value on this is it pulls out all the active computers and restarts you're selected service.  This helped us on an issue where our remote access software ScreenConnect started dropping out of our console.  A bug in their keep alives is causing the issue and the temp fix is to restart the service...but sometimes it's hard to remember what's missing so this goes through all computers active in your domain and restarts the service.

$today = Get-Date
$cutoffdate = $today.AddDays(-15)

Get-ADComputer  -Properties * -Filter {LastLogonDate -gt $cutoffdate}|Select -Expand DNSHostName  | out-file C:\All-Computers.txt

$computers = get-content "C:\All-Computers.txt"
$amount = $computers.count
$a=0

foreach ($computer in $computers) {
       $a++
       Invoke-Command -ComputerName $computer { Restart-Service -Name 'ScreenConnect Client (f95335af7be34c6f)' } -ErrorAction SilentlyContinue
       Write-Progress -Activity "Working..." -CurrentOperation "$a Complete of $amount" -Status "Please wait.  Restarting service."

}

 

Enjoy!