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

后端 未结 4 924
遇见更好的自我
遇见更好的自我 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 11:06

    Thanks @Joey. It's what I am looking for.

    I just bring some improvements:

    • to take into account multiple processes
    • to avoid reaching the timeout when all processes have terminated
    • to package the whole in a function

    function Stop-Processes {
        param(
            [parameter(Mandatory=$true)] $processName,
                                         $timeout = 5
        )
        $processList = Get-Process $processName -ErrorAction SilentlyContinue
        if ($processList) {
            # Try gracefully first
            $processList.CloseMainWindow() | Out-Null
    
            # Wait until all processes have terminated or until timeout
            for ($i = 0 ; $i -le $timeout; $i ++){
                $AllHaveExited = $True
                $processList | % {
                    $process = $_
                    If (!$process.HasExited){
                        $AllHaveExited = $False
                    }                    
                }
                If ($AllHaveExited){
                    Return
                }
                sleep 1
            }
            # Else: kill
            $processList | Stop-Process -Force        
        }
    }
    

提交回复
热议问题