Windows admin PowerShell

Stop or restart a service on many computers

Stop, start or restart one Windows service on a list of computers through PowerShell remoting, with the status of each computer in the result.

LanguagePowerShell
What it does to the systemMakes changes. Test it on one computer first.

A service hangs on a group of computers, or a setting needs a service restart to take effect. Doing it by hand per computer does not scale.

This script stops, starts or restarts one service on each computer in a list. It returns the status of the service after the action.

PowerShell
<#
  Stop, start or restart a service on many computers.
  Needs WinRM on the targets and local administrator rights there.
  Example: .\Set-RemoteService.ps1 -ComputerName PC01, PC02 -ServiceName Spooler -Action Restart -WhatIf
#>
[CmdletBinding(SupportsShouldProcess = $true)]
param(
    [Parameter(Mandatory = $true)]
    [string[]]$ComputerName,

    # The service name, not the display name. Example: Spooler
    [Parameter(Mandatory = $true)]
    [string]$ServiceName,

    [ValidateSet('Restart', 'Stop', 'Start')]
    [string]$Action = 'Restart'
)

# This block runs on each remote computer.
$work = {
    param($name, $action)
    $ErrorActionPreference = 'Stop'
    switch ($action) {
        'Restart' { Restart-Service -Name $name -Force }
        'Stop'    { Stop-Service -Name $name -Force }
        'Start'   { Start-Service -Name $name }
    }
    (Get-Service -Name $name).Status.ToString()
}

foreach ($computer in $ComputerName) {
    if (-not $PSCmdlet.ShouldProcess($computer, "$Action service $ServiceName")) { continue }

    $row = [ordered]@{ ComputerName = $computer; Service = $ServiceName; Action = $Action; Status = ''; Error = '' }
    try {
        $row.Status = Invoke-Command -ComputerName $computer -ScriptBlock $work -ArgumentList $ServiceName, $Action -ErrorAction Stop
    }
    catch {
        $row.Error = $_.Exception.Message
    }
    [pscustomobject]$row
}

How to use it

  1. Save the script as Set-RemoteService.ps1.
  2. Find the service name with Get-Service. Use the Name column, not DisplayName.
  3. Run it with -WhatIf first to check the list of computers.
  4. Run it on one computer without -WhatIf. Then use the full list.
  5. For a list, use -ComputerName (Get-Content C:\Temp\computers.txt) with one name per line.

Good to know

  • -Force also stops the services that depend on this one. A restart starts them again. A stop does not.
  • Do not restart the WinRM service this way. The script uses WinRM for its connection.
services Restart-Service Invoke-Command remoting bulk
✉

Get new articles in your inbox

SCCM guides, AI tools, automation tips — sent when published. No spam.