Windows服务和Stop-Process cmdlet的有趣问题

时间:2012-10-02 21:10:10

标签: powershell process windows-services cmdlet

我们在这里有一些自制的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。有没有人见过像这样的问题?

1 个答案:

答案 0 :(得分: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
}