Listing Remote Services without using WMI
WMI seems to get recommended for most "remote" queries in powershell. This is due in large part because the get-wmiobject cmdlet includes built in support for querying remote machines. However, I've found that WMI can be slow and whenever I find a dotnet alternative, I like to compare the speed of each method.
One of my scripts remotely queries the list of services running looking for status of a particular antivirus services. For the longest time, I relied on WMI and the -filter parameter. Recently I saw information on the [serviceprocess.servicecontroller] class and decided to give it ago. Suffice to say the performance difference is huge! Here's both versions along with results of measure-command:
WMI:
$cn = "testmachine"
$serv = gwmi -co $cn -class win32_service
Now let's wrap it with measure-command and see how long it's taking (on my system):
84# measure-Command {
>> $cn = "testmachine"
>> $serv = gwmi -co $cn -class win32_service
>> }
>>
Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 375
Ticks : 3755809
TotalDays : 4.34700115740741E-06
TotalHours : 0.000104328027777778
TotalMinutes : 0.00625968166666667
TotalSeconds : 0.3755809
TotalMilliseconds : 375.5809
NET:
$cn = "testmachine"
[system.reflection.assembly]::LoadWithPartialName("system.serviceprocess") | out-null
$serv = [serviceprocess.servicecontroller]::GetServices($cn)
And with measure-command:
92# measure-Command {
>> $cn = "testmachine"
>> [system.reflection.assembly]::LoadWithPartialName("system.serviceprocess") | out-null
>> $serv = [serviceprocess.servicecontroller]::GetServices($cn)
>> }
>>
Days : 0
Hours : 0
Minutes : 0
Seconds : 0
Milliseconds : 25
Ticks : 259210
TotalDays : 3.00011574074074E-07
TotalHours : 7.20027777777778E-06
TotalMinutes : 0.000432016666666667
TotalSeconds : 0.025921
TotalMilliseconds : 25.921
As you can see the speed is quite measurable. I ran this several times on my system and the results were consistent.
If you look at the output from each command, you'll notice that they each return a different set of properties, so you can't always find a direct drop in replacement for WMI, but in my case, the net classes had the properties I was interested in.
gaurhoth