[英]How kill a process using powershell without getting errors when the process does not exist
I want to kill the nodepad process if it exists.如果存在,我想终止 nodepad 进程。 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.我觉得它应该是沉默的,因为它不是一个错误,object应该是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. PS:我需要关闭记事本,因为当我以非交互方式安装 ClamAV 时,它会创建带有用户手册的记事本。 I could not find a way to tell ClamAV not to open the user manual.
我找不到告诉 ClamAV 不要打开用户手册的方法。
Just add -ErrorAction SilentlyContinue
.只需添加
-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
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..." }
or...或者...
Stop-Process -Name "chrome" -Force -ErrorAction SilentlyContinue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.