11-18-2010
Downloads: 758
File size: 2kB
Views: 4,234
Embed
 |
Restart-Service Remotely |
- function Restart-ServiceEx {
- [CmdletBinding( SupportsShouldProcess=$true, ConfirmImpact='High')]
- param(
- $computername = 'localhost',
- $service = 'Spooler',
- $credential = $null
- )
-
-
- $errorcode = 'Success,Not Supported,Access Denied,Dependent Services Running,Invalid Service Control'
- $errorcode += ',Service Cannot Accept Control, Service Not Active, Service Request Timeout'
- $errorcode += ',Unknown Failure, Path Not Found, Service Already Running, Service Database Locked'
- $errorcode += ',Service Dependency Deleted, Service Dependency Failure, Service Disabled'
- $errorcode += ',Service Logon Failure, Service Marked for Deletion, Service No Thread'
- $errorcode += ',Status Circular Dependency, Status Duplicate Name, Status Invalid Name'
- $errorcode += ',Status Invalid Parameter, Status Invalid Service Account, Status Service Exists'
- $errorcode += ',Service Already Paused'
-
-
- if ($credential) {
- $service = Get-WmiObject Win32_Service -ComputerName $computername -Filter "name=""$service""" -Credential $credential
- } else {
-
- $service = Get-WmiObject Win32_Service -ComputerName $computername -Filter "name=""$service"""
- }
-
-
- $servicename = $service.Caption
- if ($service.started) {
-
- if ($pscmdlet.ShouldProcess($computername, "Restarting Service '$servicename'")) {
-
- $rv = $service.StopService().ReturnValue
- if ($rv -eq 0) {
-
- $rv = $service.StartService().ReturnValue
- }
-
- $errorcode.Split(',')[$rv]
- }
- } else {
-
- if ($pscmdlet.ShouldProcess($computername, "Starting Service '$servicename'")) {
- $rv = $service.StartService().ReturnValue
- $errorcode.Split(',')[$rv]
- }
- }
- }
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.