sqlpowershellget-wmiobjectapproximate

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


Recently I discovered that one can issue sql queries to WmiObject like this:

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

I would like to further limit the output containing the CommandLine arguments, something like:

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

or

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

However this does not return any answers back. How can I formulate approximate match queries there? Sure I can do

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

But that does not look elegant.

EDIT: There's a glassfish running among my processes (if I remove "CommandLine like ...": enter image description here


Solution

  • This one:

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

    ... uses the correct syntax, the wildcard char in WQL is indeed %.


    If you want to pass a variable substring to the query, make sure you escape quotation marks and backslashes with another backslash:

    # 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}%'"