WMI Script to List Services

http://www.computerperformance.co.uk/vbscript/wmi_services.htm 這文章太好了。。

' Service.vbs
' Sample script to List services N-Z
' www.computerperformance.co.uk/
' Author Guy Thomas http://computerperformance.co.uk/
' Version 1.5 December 2010
' -------------------------------------------------------'
Option Explicit
Dim objWMIService, objItem, objService, strServiceList
Dim colListOfServices, strComputer, strService

'On Error Resume Next

' ---------------------------------------------------------
' Pure WMI commands
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery _
("Select * from Win32_Service ")

' WMI and VBScript loop
For Each objService in colListOfServices
If UCase(Left(objService.name,1)) >"N" then
strServiceList = strServiceList & vbCr & _
objService.name

End if
Next

WScript.Echo strServiceList

' End of Example WMI script to list services


From a WMI perspective

1) If you are experienced with WMI, then the two features concentrate on are, Win32_Service and objService.name.

2)  If you are new to WMI then you will soon appreciate that all WMI scripts begin by employing winmgmts to access the root of the CIM library :
Set objWMIService = GetObject("winmgmts:" & strComputer & "\root\cimv2")

2) WMI often requires security clearance in order to query the other machine's hardware, this is why we add :  & "{impersonationLevel=impersonate}!\\" _  

3) Set colComputer = objWMIService.ExecQuery _ is a standard WMI phrase to prepare for the WQL command:  Select * from Win32_Service
".  The part we are particularly interested in is _Service.  Win32 has dozens of properties, here we need to query not the process, but the Service component.

From a VBScript perspective

4) What makes scripting so powerful is the speed with which VBScript loops through an array of objects or properties, in this instance the code to look out for is: For Each....In... Next. 

5)  I am particularly proud of the this command:strServiceList = strServiceList & vbCr & objService.name.  In scripting terms it's primitive, almost a non-entity, but to me it makes the output easier to read.

6) The only property of objService that we are interested in is, .Name. However, we could have substituted other properties, for example .State or .Status.

7) As I discussed at the outset, I deliberately decided to only display a subset of all possible services, I chose to filter with the command, If UCase(Left(objService.name,1)) >"N" then...  Incidentally, there is hardly a script that cannot be fine-tuned with an, If ... Then.. End If. statement.

8)  You could take a different road and output the service information to a file.  VBScript has all the tools you need to create a file and write a service on each line.  In that example, you would not need the If..Then filter.



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章