Monthly Archive

Categories

Filter early and WQL

What’s wrong with this:

Get-CimInstance -ClassName Win32_Service |
where {$_.State -eq 'Running' -and $_.StartName -notlike 'LocalSystem' -and $_.StartName -notlike 'NT Authority*'} |
select PSComputerName, Name, DisplayName, State, StartName

 

Nothing except that its inefficient. if you ran this against a remote machine the filtering would happen on the local machine AFTER you’d dragged everything across the network. May not matter for a few machines but when you get to hundreds or thousands of machines it will have an impact

 

You need to use a filter. First try would be something like this:

Get-CimInstance -ClassName Win32_Service  -Filter "State = 'Running' AND StartName != 'LocalSystem' AND NOT StartName LIKE 'NT Authority%'"|
select PSComputerName, Name, DisplayName, State, StartName

 

Unfortunately any services with a NULL StartName will also be filtered out

 

This will work

Get-CimInstance -ClassName Win32_Service  -Filter "State = 'Running' AND Startname != 'LocalSystem' AND StartName != 'NT AUTHORITY\\LocalService' AND StartName != 'NT AUTHORITY\\NetworkService'"|
select PSComputerName, Name, DisplayName, State, StartName

 

Same results are obtained with Get-WmiObject

Comments are closed.