-->

WQL in filter doesn't work

2019-02-23 12:53发布

问题:

I'm trying to do something like:

Get-WmiObject Win32_NetworkAdapterConfiguration `
    -Filter "DefaultIPGateway!=NULL"

But I have an error:

Get-WmiObject : Invalid query At line:1 char:14 + Get-WmiObject <<<< Win32_NetworkAdapterConfiguration -Filter "DefaultIPGateway!=NULL" + CategoryInfo : InvalidOperation: (:) [Get-WmiObject], ManagementException + FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand

It's strange, because when I try to get type of DefaultIPGateway values. It's System.Array for the existent values:

PS> $result[0].DefaultIPGateway.Gettype()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String[]                                 System.Array

And a NULL for the nonexistent values:

PS> $result[1].DefaultIPGateway.GetType()
You cannot call a method on a null-valued expression.
At line:1 char:36
+ $result[1].DefaultIPGateway.GetType <<<< ()
    + CategoryInfo          : InvalidOperation: (GetType:String) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

Could someone help me to understand why my WQL doesn't work and what I should do to make it go?

回答1:

I'm not sure how to make the filter query work as I don't know how to access the array elements to check them, but have a workaround:

Get-WmiObject Win32_NetworkAdapterConfiguration | Where-Object { $_.DefaultIPGateway -ne $null }

This way, powershell will be responsible for filtering the objects returned from the query, rather than WMI doing it during retrieval.



回答2:

WQL-queries does not support array-properties.

Note WQL does not support queries of array datatypes.

Source: Querying with WQL @ MSDN

The solution is to filter out the objects with null-value using PowerShell's Where-Object cmdlet.

Get-WmiObject -Class Win32_NetworkAdapterConfiguration |
Where-Object { $_.DefaultIPGateway }