Powershell - 运行 CMD 命令 - 通配符抛出错误

Powershell - Running Command on CMD - Wildcards Throw Error

我正在尝试通过 CMD 运行 以下 Powershell 命令:

powershell -command "Get-WmiObject Win32_Process | Where-Object {$_.CommandLine -like \"*C:\Windows\Test*\" } | Select-Object ProcessName, CommandLine"

上面的命令 运行 直接在 Powershell 上没问题,但只有当我尝试在 CMD 上 运行 时才会出现问题。在我的测试中,我发现 * 符号无法正确处理,我试图在符号前加一个反斜杠进行测试,但没有成功。有没有办法让它与 CMD 中的 * 符号一起使用?

编辑: 该命令用于查看包含命令行为C:\Windows\Test

的进程

更简单,不需要 PowerShell:

wmic process where "commandline like '%c:\windows\test%'" get name, commandline

为了完整起见,为了保持主题正确,使用 cmd.exe 中的 PowerShell,我会更像这样:

powershell -noprofile "get-ciminstance -query \"select * from win32_process where commandline like '%c:\windows\test%'\" | select-object -property processname, commandline"

比调用 Windows PowerShell CLI (powershell.exe) 更简单、更高效,但值得注意的是:

  • wmic.exe CLI 已 弃用 WMIC is deprecated. 打印证明自 Windows 10 20H2 起调用其命令行帮助 (wmic /?) 时为红色;然而,奇怪的是,docs 没有 提及弃用。也就是说,wmic.exe 可能不会消失。

  • 然而,毫无疑问,来自内部 PowerShell CIM cmdlet(例如,Get-CimInstance) 更可取,[1] 尤其是因为它们 return 丰富 对象 而不仅仅是 正文.


至于你试过的

  • 您的命令 cmd.exe 开始工作(相反,not 来自 PowerShell,因为在 PowerShell 中你需要 `""" - 而不是 \" - 来嵌入 " "..." 字符串中的字符)

  • 唯一的问题是执行 Get-WmiObject 调用的 powershell.exe 进程 总是包含在搜索结果中 ,因为它本身包含搜索词。

因此,唯一需要的调整是从结果中排除powershell.exe过程本身,使用automatic $PID variable,反映了会话自身的进程ID:

  • 注意:出于上述原因,我使用 Get-CimInstance 而不是 Get-WmiObject。注意添加了 Where-Object ProcessId -ne $PID 管道段。
powershell -c "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like \"*C:\Windows\Test*\" } | Where-Object ProcessId -ne $PID | Select-Object ProcessName, CommandLine"

一个稍微更有效的替代方法是 在 WMI 源 上过滤,使用 Get-CimInstance-Filter 参数,它接受(部分) WQL 查询(注意使用 % 作为通配符,并且需要 double 文字 \ 实例;作为副作用, Where-Object ProcessId -ne $PID 不再需要过滤器):

powershell -c "Get-CimInstance Win32_Process -Filter 'CommandLine like \"%C:\Windows\Test%\"' | Select-Object ProcessName, CommandLine"

[1] CIM cmdlet(例如,Get-CimInstance)取代了 PowerShell v3(2012 年 9 月发布)中的 WMI cmdlet(例如,Get-WmiObject)。因此,应该避免使用 WMI cmdlet,尤其是因为 PowerShell (Core) (v6+),所有未来的努力都将投入其中,甚至 都没有 它们了。但是请注意,WMI 仍然是 CIM cmdlet 的基础。有关详细信息,请参阅 this answer