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

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

    @jmp242 - the generic System.Object type does not contain the CloseMainWindow method, but statically casting the System.Diagnostics.Process type when collecting the ProcessList variable works for me. Updated code (from this answer) with this casting (and looping changed to use ForEach-Object) is below.

    function Stop-Processes {
        param(
            [parameter(Mandatory=$true)] $processName,
                                         $timeout = 5
        )
        [System.Diagnostics.Process[]]$processList = Get-Process $processName -ErrorAction SilentlyContinue
    
        ForEach ($Process in $processList) {
            # Try gracefully first
            $Process.CloseMainWindow() | Out-Null
        }
    
        # Check the 'HasExited' property for each process
        for ($i = 0 ; $i -le $timeout; $i++) {
            $AllHaveExited = $True
            $processList | ForEach-Object {
                If (-NOT $_.HasExited) {
                    $AllHaveExited = $False
                }                    
            }
            If ($AllHaveExited -eq $true){
                Return
            }
            Start-Sleep 1
        }
        # If graceful close has failed, loop through 'Stop-Process'
        $processList | ForEach-Object {
            If (Get-Process -ID $_.ID -ErrorAction SilentlyContinue) {
                Stop-Process -Id $_.ID -Force -Verbose
            }
        }
    }
    

提交回复
热议问题