使用 powershell 识别进程 - 查询选项满足 CommandLine like '%pattern%'

Identify process with powershell -Query option satisfying CommandLine like '%pattern%'

最近我发现可以像这样向 WmiObject 发出 sql 查询:

Get-WmiObject -Query "SELECT * FROM Win32_Process WHERE Name='java.exe'"

我想进一步限制包含 CommandLine 参数的输出,例如:

Get-WmiObject -Query "SELECT * FROM Win32_Process WHERE Name='java.exe' AND CommandLine like '%glassfish%'"

Get-WmiObject -Query "SELECT * FROM Win32_Process WHERE Name='java.exe' AND CommandLine like '*glassfish*'"

然而这 return 没有任何回复。我如何在那里制定近似匹配查询?当然可以

Get-WmiObject -Query "SELECT * FROM Win32_Process WHERE Name='java.exe'" | Where-Object { $_.CommandLine -match "glassfish" }

但这看起来并不优雅。

编辑:我的进程中有一个 glassfish 运行(如果我删除“CommandLine like ...”:

这个:

Get-WmiObject -Query "SELECT * FROM Win32_Process WHERE Name='java.exe' AND CommandLine like '%glassfish%'"

... 使用正确的语法,WQL 中的通配符字符确实是 %.


如果要将可变子字符串传递给查询,请确保用另一个反斜杠转义引号和反斜杠:

# define substring to looks for
$cmdLineSubstring = 'glassfish'

# escape quotes and backslashes
$cmdLineSubstring = $cmdLineSubstring -replace '[\\p{Pi}\p{Pf}''"]','$0'

$query = "SELECT * FROM Win32_Process WHERE Name = 'java.exe' AND CommandLine LIKE '%${cmdLineSubstring}%'"