如果冻结,则杀死进程

时间:2019-02-22 15:29:05

标签: powershell

如果要冻结Chrome,我想杀死它;因此,我为PowerShell编写了脚本,并将其与在每小时运行的“任务管理器”中安排的任务链接。问题在于它不仅会冻结Chrome,而且总是会杀死Chrome。 该脚本有什么问题?

$response = Get-Process -Name chrome |
            Select-Object -ExpandProperty Responding

if ($response -ne 'True') {
    taskkill /f/im chrome
} else {
    Write-Host "Its Good"
    exit
}

2 个答案:

答案 0 :(得分:0)

PowerShell脚本的扩展名为.ps1。而且您的条件中有一个反模式:

$response -ne 'True'

$response是布尔值,因此它是不是。您不应该将它与字符串进行比较。

我建议这样,因为chrome产生了很多进程:

foreach ($chrome in Get-Process -Name chrome) {
    if (-not $chrome.Responding) {
        $chrome | Stop-Process -Force
    }
}

答案 1 :(得分:0)

在您的脚本中: 响应的属性是一个布尔值。 变量$ response是一个包含布尔值(如果您正在运行多个Chrome进程)的数组或一个布尔值(如果您仅正在运行一个Chrome进程)

当你写的时候 if ($response -ne 'True') 您说:“如果$ response数组不等于字符串'True'”。 编辑:经过测试,感谢@ TheIncorrigible1,$ response被转换为字符串

要执行您的请求,我建议以下内容:

$response = get-process -Name chrome


$response | ForEach-Object {
    if ($_.Responding) {
    #Your process is responding 'no problemo'
    Write-Host "$($_.ProcessName) is responding"
    }
    else {
    #Your process is not responding
    $_ | stop-process -force #edited after testing
    Write-Host "$($_.ProcessName) killed"
    }

}

希望这会有所帮助:)

相关问题