代码之家  ›  专栏  ›  技术社区  ›  puravidaso

当进程不存在时,如何使用powershell杀死进程而不出错

  •  0
  • puravidaso  · 技术社区  · 3 年前

    如果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不要打开用户手册。

    1 回复  |  直到 3 年前
        1
  •  9
  •   Michal Rosenbaum    3 年前

    只需添加 -ErrorAction SilentlyContinue 这个更简单,如果进程不存在,不会提示任何错误。

    Get-Process -Name notepad -ErrorAction SilentlyContinue | Stop-Process -Force
    
        2
  •  2
  •   Cpt.Whale    3 年前

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

    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..." }
    
        3
  •  0
  •   Thierry Brémard    2 年前

    或者。。。

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

    如果你用这个 Gitlab 注意它有一个 PowerShell运行程序的错误 ,您可以通过在括号内封装来解决这个问题,从而得到:

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

    来源: Gitlab powershell issue breaking on ErrorAction