How kill a process using powershell without getting errors when the process does not exist

8.1k Views Asked by At

I want to kill the nodepad process if it exists. If I use this:

PS C:\> get-process -name notepad | Stop-Process -Force

I will get an error when the process does not exist.

get-process : Cannot find a process with the name "notepad". Verify the process name and call the cmdlet again.
At line:1 char:1
+ get-process -name notepad | Stop-Process -Force
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (notepad:String) [Get-Process], ProcessCommandException
    + FullyQualifiedErrorId : NoProcessFoundForGivenName,Microsoft.PowerShell.Commands.GetProcessCommand

I feel it should be silent, as it is not an error, the object should be null.

I know I could do:

PS C:\> get-process | where { $_.processname -eq 'notepad' } | Stop-Process -Force

but I prefer a simple way if it exists. Thanks.

PS: I need to kill the notepad because when I non-interactively install ClamAV, it create the notepad with a user manual. I could not find a way to tell ClamAV not to open the user manual.

3

There are 3 best solutions below

0
On BEST ANSWER

Just add -ErrorAction SilentlyContinue. This one is simpler and does not prompt any erros if process does not exist.

Get-Process -Name notepad -ErrorAction SilentlyContinue | Stop-Process -Force
7
On

I suggest checking if the notepad process is the one you want first before just force-ending all notepad processes on the system:

Try {
    (Get-WmiObject win32_process -Filter "name='notepad.exe'" | 
    Where commandline -like '*\path\to\manual.txt'
    ).Terminate()
}
# Handle "can't call method on null" error:
Catch [System.SystemException] { "Manual.txt process not found, skipping..." }
0
On

or ...

Stop-Process -Name "chrome" -Force -ErrorAction SilentlyContinue

And if you are using this with Gitlab beware that it has a bug with PowerShell runner, that you can work around by encapsulation inside parenthesis resulting in:

(Stop-Process -Name "chrome" -Force -ErrorAction SilentlyContinue)

source: Gitlab powershell issue breaking on ErrorAction