0
votes

I'm writing a simple WMI query in the powershell ISE. I want to get just two fields, but I get more

Get-WmiObject -Query "select DisplayName, State from Win32_Service"

And what I get is a list of results, each has the next fields,

__GENUS          : 2
__CLASS          : Win32_Service
__SUPERCLASS     : 
__DYNASTY        : 
__RELPATH        : 
__PROPERTY_COUNT : 2
__DERIVATION     : {}
__SERVER         : 
__NAMESPACE      : 
__PATH           : 
DisplayName      : Windows Font Cache Service
State            : Running

I noticed that the fields all start with a double underscore, not sure if it means anything. I know I can get a better result with

Get-WmiObject -Class Win32_Service | Select-Object DisplayName, State

However, I would like to add a where clause to this query, so I'm trying to use the -Query option.

2
You can still use a WHERE clause: get-wmiobject -query "select DisplayName, State from Win32_service WHERE ..." | select-object DisplayName, State - Tomalak
Or you can use where-object, for example get-wmiobject -class win32_service | where-object -Property State -EQ -Value "Stopped" | select-object DisplayName, State. - Andrew Morton
This is part of Get-WmiObject's format file that dictates how objects from that cmdlet get printed to the console. You would either have to manually edit that, or the easy way is to just use the Select-Object cmdlet. - Maximilian Burszley

2 Answers

2
votes

These fields are part of the internal WMI metadata. You can't stop the legacy WMI cmdlets from returning them, but you can obviously use Select-Object to create a copy without them, or Format-Table, etc to display only what you want to see.

In any case, the 'CIM' cmdlets are the preferred option now. So in your case, you should use this command instead:

Get-CimInstance -Query "select DisplayName, State from Win32_Service"

Get more information here:

Get-CimInstance

1
votes

I've read that using the linq like .where() method is much faster than using Where-Object. This works for me. Not sure what else you're looking for.

  (Get-WmiObject -Query "select DisplayName, State from Win32_Service").Where( {$_.State -eq 'Stopped'}) | select Displayname, State

Or You will need to use a WMI based query to filter first.

Get-WmiObject -Query "select DisplayName, State from Win32_Service where State ='Stopped'" | select Displayname, State