如何杀死运行给定可执行文件的进程?

时间:2021-03-05 18:32:04

标签: powershell process kill

我想杀死一份工作。首先,我需要它的进程 ID,所以我执行:

get-process

我得到了一大堆流程。好的,我只想要一个特定的过程,所以我使用:

get-process | select-string -pattern "nginx"

这给了我这个对象:

System.Diagnostics.Process (nginx)

我该怎么办?当我要求所有进程时,我怎样才能漂亮地打印它以给我相同的输出行?当我为给定的执行过程 grep 时,我基本上只想要这个:

166      11     2436       8244       0.13  24196   1 nginx                                                        

1 个答案:

答案 0 :(得分:4)

Select-String 可能不是你想用来钉这个特定钉子的锤子(见下文):-)

Get-Process 有一个带通配符的 -Name 参数:

Get-Process -Name nginx
# or
Get-Process -Name *nginx*

要终止进程,请直接在对象上调用 Kill()

$nginxProcess = Get-Process nginx |Select -First 1
$nginxProcess.Kill()

... 或者简单地将流程实例通过管道传输到 Stop-Process:

Get-Process -Name nginx |Stop-Process

如您所见,我们实际上从未需要定位或传递进程 ID - Process 对象已经嵌入了该信息,并且 *-Process cmdlet 旨在运行 一致 - PowerShell 完全是关于命令组合,这是一个例子。

话虽如此,Stop-Process 也完全能够仅通过名称杀死进程:

Stop-Process -Name nginx

我怎么知道 *-Process cmdlet 有 -Name 参数?

除了阅读help files and documentation(我明白了,我也不想阅读任何东西,除非我绝对必须 ;-)),这是一种快速了解cmdlet 公开的参数是通过运行 Get-Command <commandName> -Syntax:

PS ~> Get-Command Stop-Process -Syntax

Stop-Process [-Id] <int[]> [-PassThru] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>]

Stop-Process -Name <string[]> [-PassThru] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>]

Stop-Process [-InputObject] <Process[]> [-PassThru] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>]

输出向我们展示了 3 个不同的“参数集”(命令接受的参数输入的组合),以及我们可以传递给它的必需参数和可选参数。


Select-String 有什么问题?

Select-String cmdlet 是与 grep 同源的 PowerShell - 它接受一些输入,并根据您提供的任何模式对其执行正则表达式匹配。

但是 grep 仅在您操作 字符串 时才有用 - 正如您已经发现的,Get-Process 返回结构化的 .NET 对象,而不是平面字符串。

相反,PowerShell 惯用方法是过滤数据,使用 Where-Object cmdlet:

Get-Process | Where-Object Name -like '*nginx*'

在这里,我们指示 Where-Object 只让具有 Name 属性的对象通过,其值必须满足通配符模式 *nginx*

Where-Object 还支持任意过滤器表达式,通过接受脚本块 - PowerShell 会将正在评估的当前管道对象分配给 $_(和 $PSItem):

Get-Process | Where-Object { $_.Name -like '*nginx*' }

...你可以扩展到任何你需要的程度:

# Only let them through if a specific user is executing
Get-Process | Where-Object { $_.Name -like '*nginx*' -and $env:USERNAME -ne 'Quarkly'}