简体   繁体   中英

Stop remote service using PowerShell

I've a script that stops remote services through WMI :

(get-service -ComputerName $server_ip -Name $service).Stop()

I want to force a service after five tries. I have build a counter, but what is the command to force a stop?

If you have winRM enabled you can use the following:

Invoke-Command -ComputerName server1 -ScriptBlock {
    Stop-Service $args[0] -Force } -ArgumentList $service

If by "force a stop" you mean you want to forcibly terminate (ie kill) the service process you could try killing the process via its PID:

$server  = '1.2.3.4'
$service = 'name'

Invoke-Command -Computer $server -ScriptBlock {
  param($svc)

  $Error.Clear()

  1..5 | % {
    Stop-Service -Name $svc
    if ($?) { break }  # exit from loop if previous command succeeded
  }

  if ($Error.Count -eq 5) {
    $pid = (Get-WmiObject Win32_Service -Filter "Name='$svc'").ProcessId
    (Get-Process -Id $pid).Kill()
  }
} -ArgumentList $service

Running the code via Invoke-Command is to avoid multiple remote connections.

This should work even for services that have the NOT_STOPPABLE flag set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM