2

我们这里有一些自制的 Windows 服务。其中一个是有问题的,因为它不会总是在被问到时停止。它有时会卡在“停止”状态。

使用 powershell 我们正在检索其 PID 并使用 Stop-Process cmdlet 来终止相关进程,但这也不起作用。

相反,我们会收到一条名为服务的消息,该服务System.ServiceProcess.ServiceController.Name显然不是我们的服务,但它引用的 PID 是。

以下是我们为停止服务所做的工作。首先,我们使用 Get-Service cmdlet:

$ServiceNamePID = Get-Service -ComputerName $Computer | where { ($_.Status -eq 'StopPending' -or $_.Status -eq 'Stopping') -and $_.Name -eq $ServiceName}

然后,使用该 ServiceNamePID,我们获取 PID 并在 Stop-Process cmdlet 中使用它

$ServicePID = (get-wmiobject win32_Service -ComputerName $Computer | Where { $_.Name -eq $ServiceNamePID.Name }).ProcessID
Stop-Process $ServicePID -force

那是 Stop-Process cmdlet 大喊大叫的Cannot find a process with the process identifier XYZ时候,实际上 PID XYZ服务的正确进程 ID,根据任务管理器。有没有人见过这样的问题?

4

1 回答 1

5

为了停止远程机器上的进程,请使用远程处理,例如

 Invoke-Command -cn $compName {param($pid) Stop-Process -Id $pid -force } -Arg $ServicePID

这需要在远程 PC 上启用远程处理,并且本地帐户在远程 PC 上具有管理员价格。

当然,一旦您使用远程处理,您就可以使用远程处理来执行脚本,例如:

Invoke-Command -cn $compName {
    $ServiceName = '...'
    $ServiceNamePID = Get-Service | Where {($_.Status -eq 'StopPending' -or $_.Status -eq 'Stopping') -and $_.Name -eq $ServiceName}
    $ServicePID = (Get-WmiObject Win32_Service | Where {$_.Name -eq $ServiceNamePID.Name}).ProcessID
    Stop-Process $ServicePID -Force
}
于 2012-10-03T01:09:34.660 回答