How to Correctly Check if a Process is running and Stop it

后端 未结 4 886
遇见更好的自我
遇见更好的自我 2021-01-30 10:26

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:

<
4条回答
  •  孤街浪徒
    2021-01-30 10:55

    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
    

提交回复
热议问题