windows - 当进程不存在时如何使用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
推荐阅读
- reactjs - 我将如何使用 usecontext 进行搜索栏过滤
- php - PHPOfficePhpSpreadsheet 找不到空单元格(没有值或 0)
- image - 将图片放在乳胶中
- c++ - ifstream 不会读取嵌套循环
- ethereum - Ropsten 测试网络的 Solidity - 未捕获的错误:无效地址
- flutter - Flutter 返回分类选项卡和项目的列表
- node.js - Yarn 3 和 Node 17:文件扩展名解析失败?
- react-native - 如何创建具有特定版本的 react-native 项目
- yarnpkg - yarn berry foreach 工作空间未按 package.json 中指定的顺序构建包
- dart - Dart 中的稳定列表集差异