简体   繁体   English

使用PowerShell停止远程服务

[英]Stop remote service using PowerShell

I've a script that stops remote services through WMI : 我有一个脚本,可以通过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: 如果启用了winRM,则可以使用以下命令:

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: 如果通过“强制停止”来表示您要强制终止(即终止)服务进程,则可以尝试通过其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. 通过Invoke-Command运行代码是为了避免多个远程连接。

This should work even for services that have the NOT_STOPPABLE flag set. 即使对于已设置NOT_STOPPABLE标志的服务,这也应该起作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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