Restart-Service Remotely


posted by Tobias
11-18-2010

Downloads: 1,215
File size: 2kB
Views: 7,476

Embed
Restart-Service Remotely
  1. function Restart-ServiceEx
  2.     [CmdletBinding( SupportsShouldProcess=$true, ConfirmImpact='High')] 
  3.     param
  4.     $computername = 'localhost'
  5.     $service = 'Spooler'
  6.     $credential = $null 
  7.     
  8.  
  9. # create list of clear text error messages 
  10.     $errorcode = 'Success,Not Supported,Access Denied,Dependent Services Running,Invalid Service Control' 
  11.     $errorcode += ',Service Cannot Accept Control, Service Not Active, Service Request Timeout' 
  12.     $errorcode += ',Unknown Failure, Path Not Found, Service Already Running, Service Database Locked' 
  13.     $errorcode += ',Service Dependency Deleted, Service Dependency Failure, Service Disabled' 
  14.     $errorcode += ',Service Logon Failure, Service Marked for Deletion, Service No Thread' 
  15.     $errorcode += ',Status Circular Dependency, Status Duplicate Name, Status Invalid Name' 
  16.     $errorcode += ',Status Invalid Parameter, Status Invalid Service Account, Status Service Exists' 
  17.     $errorcode += ',Service Already Paused' 
  18.  
  19.     # if credential was specified, use it... 
  20.     if ($credential) { 
  21.         $service = Get-WmiObject Win32_Service -ComputerName $computername -Filter "name=""$service""" -Credential $credential 
  22.     } else
  23.         # else do not use this parameter: 
  24.         $service = Get-WmiObject Win32_Service -ComputerName $computername -Filter "name=""$service"""  
  25.     
  26.  
  27.     # if service was running already... 
  28.     $servicename = $service.Caption 
  29.     if ($service.started) { 
  30.         # should action be executed?  
  31.         if ($pscmdlet.ShouldProcess($computername, "Restarting Service '$servicename'")) { 
  32.    # yes, stop service: 
  33.             $rv = $service.StopService().ReturnValue 
  34.             if ($rv -eq 0) { 
  35.                 # ...and if that worked, restart again 
  36.                 $rv = $service.StartService().ReturnValue 
  37.             
  38.    # return clear text error message: 
  39.             $errorcode.Split(',')[$rv
  40.         }  
  41.     } else
  42.         # else if service was not running yet, start it: 
  43.         if ($pscmdlet.ShouldProcess($computername, "Starting Service '$servicename'")) { 
  44.             $rv = $service.StartService().ReturnValue 
  45.             $errorcode.Split(',')[$rv
  46.         }  
  47.     
Stop-Service, Start-Service and Restart-Service all only work locally. This script creates a new function called Restart-ServiceEx that can restart a service locally and remotely. It also demonstrates how to add support for -Whatif and -Confirm.
Copyright 2012 PowerShell.com. All rights reserved.