首页 > 解决方案 > PowerShell:杀死/查找当前用户的所有进程,白名单除外

问题描述

在我的 CI(Jenkins)奴隶上,我想在构建之后/之前杀死所有剩余的进程。(是的,我知道詹金斯试图为我做这件事,但并不总是成功)。

启发式是:

我找到了找到当前用户进程的方法,我找到了杀死进程的方法,但没有找到如何将它们组合起来(理想情况下是单线)

标签: powershell

解决方案


这就是我让 Jenkins 在构建前/构建后运行的内容(在 Windows Server 2016 上测试):
如果用作单行,则删除反引号

(Get-WmiObject -Class Win32_Process `
   | ? { ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name) -match $_.GetOwner().User } `
   | ? {$_.CommandLine -notmatch 'conhost|swarm|jenkins-.*bat' -and $_.Name -notmatch 'System Idle|^System$' } `
).Terminate()

为了直观地列出它们(我在运行上面的终止版本之前运行它),最后一行是不同的:

(Get-WmiObject -Class Win32_Process `
   | ? { ([System.Security.Principal.WindowsIdentity]::GetCurrent().Name) -match $_.GetOwner().User } `
   | ? {$_.CommandLine -notmatch 'conhost|swarm|jenkins-.*bat' -and $_.Name -notmatch 'System Idle|^System$' } `
) | Select-Object Handle,Name,CommandLine | Format-List | Out-String -width 9999

两者都通过powershell -c


推荐阅读