powershell - 通过 "Command Line"参数搜索 taskkill 的批处理脚本

标签 powershell

我需要一个批处理脚本来通过“命令行”参数(Windows 任务管理器中的“命令行”)执行任务。澄清一下 - 这些进程是 dotnet core 应用程序。它们是通过以下方式启动的:

dotnet MyDotnetCoreApp.dll xxx yyy

如果您在任务管理器下查看,

  1. 名称 = dotnet.exe

  2. 图片路径名 = C:\Program Files\dotnet\dotnet.exe

  3. 命令行 = dotnet MyDotnetCoreApp.dll xxx yyy

我需要一个批处理脚本来终止这些任务,可能使用 taskkill

选项 1 是 PID 的 Taskkill,但我的脚本如何搜索 MyDotnetCoreApp 的“命令行”参数?

选项 2 是图像名称的 taskkill?这是行不通的,因为我的服务器有很多 dotnet 核心应用程序,如果终止我的图像名称,所有 dotnet 核心进程都会被终止

我一直在研究:

https://superuser.com/questions/415360/how-do-i-find-out-command-line-arguments-of-a-running-program

https://www.itprotoday.com/powershell/powershell-contains

我无法让它工作,我不擅长 PowerShell:

Get-WmiObject Win32_Process -Filter "name = 'dotnet.exe'" | Select-Object Handle

这里会得到一个要杀死的 PID 列表。

两个挑战:

第一个挑战,我的 WHERE 子句不起作用:

Get-WmiObject Win32_Process -Filter "name = 'dotnet.exe'" | where {$_.CommandLine -like '*MyDotnetCoreApp*'} | Select-Object Handle

我进一步检查,发现这些“命令行”没有为这些 WmiObjects 填充(我的天啊!): 获取 WmiObject Win32_Process -Filter "name = 'dotnet.exe'"|选择对象 ProcessId、名称、CSName、标题、命令行、可执行路径

我后来发现如果您以管理员身份运行 Powershell,“CommandLine”会被填充!?! (Powershell 如此神秘!)

最后 - 第一个挑战被解决:

Get-WmiObject Win32_Process -Filter "name = 'dotnet.exe'" | where {$_.CommandLine -like '*MyDotnetApp*'} | Select-Object ProcessId, Name, CSName, Caption, CommandLine, ExecutablePath 

第二个挑战:如何杀死它? 找到了!!

(Get-WmiObject Win32_Process -Filter "name = 'dotnet.exe'" | where {$_.CommandLine -like '*MyDotnetCoreApp*'}).Terminate()

所以这实际上已经解决了!

最佳答案

以管理员身份运行 Powershell!从 https://learn.microsoft.com/en-us/sysinternals/downloads/psexec 下载 psexec

psexec -u Administrator -p SomeSecret powershell

然后从Powershell:

(Get-WmiObject Win32_Process -Filter "name = 'dotnet.exe'" | where {$_.CommandLine -like '*MyDotnetCoreApp*'}).Terminate()

现在作为一个单独的问题,你能做到这一行吗?下面将不起作用,因为 -Filter 中有引号!

psexec -u Administrator -p SomeSecret powershell -Command "(Get-WmiObject Win32_Process -Filter ""name = 'dotnet.exe'"" | where {$_.CommandLine -like '*MyDotnetCoreApp*'}).Terminate() "

作为 hacky 解决方法,我删除了 -Filter 子句(多么不幸,不知道如何转义引号):

psexec -u Administrator -p SomeSecret powershell -Command "(Get-WmiObject Win32_Process | where {$_.CommandLine -like '*MyDotnetCoreApp*'}).Terminate() "

关于powershell - 通过 "Command Line"参数搜索 taskkill 的批处理脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54808022/

相关文章:

powershell - 在数组创建期间调用函数以导出包含 Zip 文件的文件夹的内容

sql - 我需要找到一种方法来删除 SQL Server 备份文件夹中第三个 .bak 文件之后的所有内容

xml - 使用 PowerShell 更改 XML 中的项目(0)

arrays - 输出到CSV包含逗号

xml - 使用 PowerShell 使用变量中的节点解析 XML 文件

powershell - 如何在Powershell中迭代 “For each object that has a value”

powershell - cUrl与Invoke-WebRequest

powershell - 从命令行调用PowerShell函数

rest - Azure 网站 Kudu REST API - 身份验证

azure - 使用 Az Powershell 禁用 azure function 应用远程调试