仅在先前运行时按特定顺序启动/停止服务

时间:2014-03-02 17:58:27

标签: vbscript

sComputer = "."
Set Runninglist = CreateObject("System.Collections.ArrayList")
aTargetSvcs= Array ("pageserver","CacheServer","CrystalAPS","CrystalInputFileServer","CrystalOutputFileServer","CrystalReportApplicationServer", "JobServer_Report" )
Set oWMIService = GetObject("winmgmts:" & "{impersonationlevel=impersonate}!\\" _
& sComputer & "\root\cimv2")
Set cServices = oWMIService.ExecQuery("SELECT * FROM Win32_Service")
For Each oService In cServices
For Each sTargetSvc In aTargetSvcs
If LCase(oService.Name) = LCase(sTargetSvc) Then

If oService.State <> "Started" Then
Runninglist.Add oService.Name
  oService.StopService()    
 End If
End if
Next
Next

WScript.Sleep 3000

For Each oService In cServices
For Each sTargetSvc In Runninglist
If LCase(oService.Name) = LCase(sTargetSvc) Then
oService.StartService()
End If
Next
Next

目标:我想按此顺序从Runninglist启动服务,前提是它们先前已停止:
CrystalAPS
Crystal输入文件资源库服务器
Crystal输出文件资源库服务器
Crystal Report Application Server
Crystal Report作业服务器
Crystal Cache Server
Crystal Page Server

1 个答案:

答案 0 :(得分:0)

我试图利用两个事实:

  1. VBScript字典保持稳定的输入顺序
  2. 可以存储WMI循环对象以供以后使用
  3. 在代码中:

    Option Explicit
    
    Dim dicSrvOrd : Set dicSrvOrd = CreateObject("Scripting.Dictionary")
    dicSrvOrd.CompareMode = vbTextCompare
    Set dicSrvOrd("SQLWriter") = Nothing
    Set dicSrvOrd("Browser")   = Nothing
    Set dicSrvOrd("Alerter")   = Nothing
    
    Dim oService
    For Each oService In GetObject("winmgmts:" & "{impersonationlevel=impersonate}!\\.\root\cimv2").ExecQuery("SELECT * FROM Win32_Service")
        If dicSrvOrd.Exists(oService.Name) Then
           If "Running" = oService.State Then
              WScript.Echo "stopping", oService.Name, "(was", oService.State & ")"
              Set dicSrvOrd(oService.Name) = oService
           Else
              WScript.Echo oService.Name, oService.State
           End If
        Else
           ' WScript.Echo "don't care for", oService.Name
        End If
    Next
    WScript.Echo "--------------"
    Dim sSrv
    For Each sSrv In dicSrvOrd.Keys()
        If Not dicSrvOrd(sSrv) Is Nothing Then
           WScript.Echo "starting", dicSrvOrd(sSrv).Name
        End If
    Next
    

    输出:

    cscript 22131182.vbs
    Alerter Stopped
    stopping Browser (was Running)
    stopping SQLWriter (was Running)
    --------------
    starting SQLWriter
    starting Browser