程序问答   发布时间:2022-06-02  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了当进程不存在时,如何使用 powershell 杀死进程而不会出错大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。

如何解决当进程不存在时,如何使用 powersHell 杀死进程而不会出错?

开发过程中遇到当进程不存在时,如何使用 powersHell 杀死进程而不会出错的问题如何解决?下面主要结合日常开发的经验,给出你关于当进程不存在时,如何使用 powersHell 杀死进程而不会出错的解决方法建议,希望对你解决当进程不存在时,如何使用 powersHell 杀死进程而不会出错有所启发或帮助;

如果 nodepad 进程存在,我想杀死它。如果我使用这个

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

进程不存在时会报错。

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

我觉得它应该是沉默的,因为它不是错误,对象应该是空的。

我知道我可以做到:

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

但我更喜欢一种简单的方法,如果它存在的话。谢谢。

PS:我需要关闭记事本,因为当我以非交互方式安装 ClamAV 时,它会创建带有用户手册的记事本。我找不到告诉 ClamAV 不要打开用户手册的方法。

解决方法

只需添加 -ErrOraction SilentlyConTinue。这个比较简单,如果进程不存在也不提示任何错误。

Get-Process -Name notepad -ErrOraction SilentlyConTinue | Stop-Process -Force
,

我建议在强制结束系统上的所有记事本进程之前先检查记事本进程是否是您想要的进程:

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..." }

大佬总结

以上是大佬教程为你收集整理的当进程不存在时,如何使用 powershell 杀死进程而不会出错全部内容,希望文章能够帮你解决当进程不存在时,如何使用 powershell 杀死进程而不会出错所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。