如何在PowerShell中获取进程的Command Line属性
获取进程命令行并过滤的PowerShell解决方案
1. 获取进程的命令行属性
Get-Process cmdlet没有直接提供CommandLine属性,需通过CIM查询Win32_Process类来获取完整命令行信息,这是系统级进程属性的标准查询方式。
高效直接的查询命令
Get-CimInstance Win32_Process -Filter "Name='firefox.exe'" | Where-Object { $_.TotalProcessorTime -ne $null } | Select-Object Name, ProcessId, CommandLine
-Filter "Name='firefox.exe'":提前在CIM层面筛选Firefox进程,比管道后续过滤性能更优ProcessId对应任务管理器中的PID,CommandLine即为你需要的命令行属性
基于Get-Process的补全方案(可选)
如果习惯使用Get-Process,可通过关联CIM补全命令行:
Get-Process Firefox | Where-Object { $_.TotalProcessorTime -ne $null } | ForEach-Object { [PSCustomObject]@{ Name = $_.Name Id = $_.Id CommandLine = (Get-CimInstance Win32_Process -Filter "ProcessId=$($_.Id)").CommandLine } }
2. 过滤命令行中的特定字符串
不建议使用findstr,PowerShell原生的Where-Object(简写?)是更适配的方案——直接操作PowerShell对象,无需跨进程调用外部工具,语法统一且效率更高。
正则匹配(推荐,支持复杂规则)
筛选命令行包含1306.5.1392的进程(默认不区分大小写,严格区分用-cmatch):
Get-CimInstance Win32_Process -Filter "Name='firefox.exe'" | Where-Object { $_.TotalProcessorTime -ne $null -and $_.CommandLine -match '1306\.5\.1392' } | Select-Object Name, ProcessId, CommandLine
- 正则中
.是通配符,需转义为\.以匹配实际的点号
简单字符串包含(适合基础场景)
用-like做模糊匹配,无需转义(通配符*表示任意字符):
Get-CimInstance Win32_Process -Filter "Name='firefox.exe'" | Where-Object { $_.TotalProcessorTime -ne $null -and $_.CommandLine -like '*1306.5.1392*' } | Select-Object Name, ProcessId, CommandLine
- 区分大小写用
-clike
格式化输出(匹配示例样式)
如果需要和你给出的示例格式一致,可通过计算属性调整列名:
Get-CimInstance Win32_Process -Filter "Name='firefox.exe'" | Where-Object { $_.TotalProcessorTime -ne $null -and $_.CommandLine -match '1306\.5\.1392' } | Format-Table Name, ProcessId, @{Name='Command Line'; Expression={$_.CommandLine}} -AutoSize
内容的提问来源于stack exchange,提问作者lanz
相关产品推荐
相关产品推荐

