taskkill to differentiate 2 images by path

前端 未结 5 1913
再見小時候
再見小時候 2021-01-04 01:30

How to kill a process by name and orginiated from a particular path using taskkill?

taskkill /F /IM

certainly it cant differentiate 2 process started from t

5条回答
  •  囚心锁ツ
    2021-01-04 02:18

    Based on Joey's answer and user's comment.

    Assuming that the path of the program is C:\Dir1\file.exe. If multiple instances of the program are running, you should use the following command:

    Get-WmiObject Win32_Process |
        Where-Object { $_.Path -eq "C:\Dir1\file.exe" } |
            ForEach-Object { $_.Terminate() }
    

    Otherwise, Powershell will report an error:

    PS > (Get-WmiObject Win32_Process |
        Where-Object { $_.Path -eq "C:\Dir1\file.exe" }).Terminate()
    
    Method invocation failed because [System.Object[]] doesn't contain a method named 'Terminate'.
    

    In addition, the above command also avoids the error when no matching process is found (e.g., the Path of no process is equal to C:\Dir1\file.exe):

    PS > (Get-WmiObject Win32_Process |
        Where-Object { $_.Path -eq "C:\Dir1\file.exe" }).Terminate()
    
    You cannot call a method on a null-valued expression.
    

    If you don't like WMI:

    Get-Process |
        Where-Object { $_.Path -eq "C:\Dir1\file.exe" } |
            ForEach-Object { Stop-Process -Id $_.Id }
    

    I noticed that the Win32_Process.Terminate() and Stop-Process methods are used to forcibly terminate the process, so the process may not be able to perform any cleanup work.

    Tested in Powershell 2.0 on Windows 7 SP1.

提交回复
热议问题