【问题标题】:How kill a process using powershell without getting errors when the process does not exist当进程不存在时如何使用powershell杀死进程而不会出错
【发布时间】:2021-04-28 00:58:08
【问题描述】:

如果存在,我想杀死 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

我觉得应该是静默的,因为不是错误,对象应该是null。

我知道我能做到:

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

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

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

【问题讨论】:

    标签: windows powershell clamav


    【解决方案1】:

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

    Get-Process -Name notepad -ErrorAction SilentlyContinue | Stop-Process -Force
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 检查进程是个好主意。使用管道不应需要“找不到进程”异常。
      • @puravidaso Get-WmiObject 在未找到进程时不会返回错误,但 Terminate() 方法会返回错误,所以这就是我所捕获的。
      • 只是一个挑剔: Terminate 方法实际上并没有引发异常。当您尝试在不存在的对象上调用方法时,这是 powershell 运行时引发异常
      • 确实如此,至少在 PS7 中如此Get-Process | Get-Member
      • @Daniel 你是对的! (我不得不从 7.0.3 升级到 7.1.3)。请注意,它是一个 ScriptProperty,只是在幕后运行 (Get-CimInstance Win32_Process -Filter "ProcessId = $($this.Id)").CommandLine
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-14
      • 1970-01-01
      • 1970-01-01
      • 2014-09-25
      • 2015-02-18
      • 2021-12-02
      相关资源
      最近更新 更多