当进程不存在时,如何使用 powershell 终止进程而不会出错
How kill a process using powershell without getting errors when the process does not exist
我想终止 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..." }
我想终止 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..." }