簡體   English   中英

當進程不存在時,如何使用 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

我覺得它應該是沉默的,因為它不是一個錯誤,object應該是null。

我知道我可以這樣做:

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

或者...

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM