如何正确检查进程是否正在运行并停止它 [英] How to Correctly Check if a Process is running and Stop it

查看:90
本文介绍了如何正确检查进程是否正在运行并停止它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定进程是否正在运行(例如 FireFox)并停止它的正确方法是什么?

What is the correct way of determining if a process is running, for example FireFox, and stopping it?

我环顾四周,发现最好的方法是:

I did some looking around and the best way I found was this:

if((get-process "firefox" -ea SilentlyContinue) -eq $Null){ 
        echo "Not Running" 
}

else{ 
    echo "Running"
    Stop-Process -processname "firefox"
 }

这是理想的做法吗?如果不是,那么正确的做法是什么?

Is this the ideal way of doing it? If not, what the correct way of doing so?

推荐答案

按照您的操作方式,您需要对流程进行两次查询.Lynn 还提出了一个很好的观点,那就是首先要友善.我可能会尝试以下操作:

The way you're doing it you're querying for the process twice. Also Lynn raises a good point about being nice first. I'd probably try something like the following:

# get Firefox process
$firefox = Get-Process firefox -ErrorAction SilentlyContinue
if ($firefox) {
  # try gracefully first
  $firefox.CloseMainWindow()
  # kill after five seconds
  Sleep 5
  if (!$firefox.HasExited) {
    $firefox | Stop-Process -Force
  }
}
Remove-Variable firefox

这篇关于如何正确检查进程是否正在运行并停止它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆