PowerShell: How To Disable and/or Stop Windows Service

Disable and Stop Using Native Command ‘Set-Service’

# To disable service as well as stopping it, assuming that the service does not have dependencies

Set-Service -Name $serviceName -Status $setStatus -StartupType $setStartup -computername $computernames

# Possible error: this means the service cannot be disabled without disabling its upstream parent services
Set-Service : Cannot stop service 'windows_exporter (windows_exporter)' because it is dependent on other services.
At line:1 char:1
+ Set-Service -Name $serviceName -Status stopped -StartupType disabled  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.ServiceProcess.ServiceController:ServiceController) [Set-Service], ServiceCommandException
    + FullyQualifiedErrorId : ServiceIsDependentOnNoForce,Microsoft.PowerShell.Commands.SetServiceCommand

Using SC

$action='start' # or stop

function setService{
        $action='start' # or stop
    $computernames|%{Start-Process "$env:WINDIR\system32\sc.exe" \\$_,start,$serviceName -NoNewWindow -Wait}

setService $computerNames $serviceName $action
# To simply stop or start a service using the legacy tool SC.EXE on a list of servers
$action='start' # or stop
$computernames|%{Start-Process "$env:WINDIR\system32\sc.exe" \\$_,$action,$serviceName -NoNewWindow -Wait}

# Note: The native stop-service Powershell command does not have a computername parameter; Hence, the native command above is used as a workaround
Stop-Service : A parameter cannot be found that matches parameter name 'computername'.
At line:1 char:14
+ stop-service -computername $computernames -name $servicename -force
+              ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Stop-Service], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.StopServiceCommand
# Sample output
SERVICE_NAME: windows_exporter
        TYPE               : 10  WIN32_OWN_PROCESS
        STATE              : 3  STOP_PENDING
                                (NOT_STOPPABLE, NOT_PAUSABLE, IGNORES_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0


PS C:\Users\administrator> get-service windows_exporter -computername $computernames|select MachineName,Name,Status

MachineName   Name              Status
-----------   ----              ------
dev01 windows_exporter Stopped
dev02  windows_exporter Stopped
dev03   windows_exporter Stopped
dev04   windows_exporter Stopped

Leave a Reply

Your email address will not be published. Required fields are marked *