首页 文章

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

提问于
浏览
2

我们在这里有一些家庭酿造的窗户服务 . 其中一个是有问题的,因为当被问到时它不会总是停止 . 它有时会陷入“停止”状态 .

使用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 回答

  • 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
    }
    

相关问题