Can someone please tell me the command to stop or start a service in VBscript

Many thanks
0 Comments   [ + ] Show Comments

Comments

Please log in to comment

Rating comments in this legacy AppDeploy message board thread won't reorder them,
so that the conversation will remain readable.

Answers

1
Why not just use a batch file?

"net stop <service name>"

.....do your actions

"net start <service name>"
Answered 02/03/2005 by: aogilmor
Ninth Degree Black Belt

Please log in to comment
1
I could but I figured there would be a "proper" vbscirpt way?
Answered 02/03/2005 by: Naffcat
Senior Purple Belt

Please log in to comment
1
Hi Naffcat,

If you are using wise you can do the same action from services tab.
Answered 02/04/2005 by: adaptability
Orange Senior Belt

Please log in to comment
1
[8D]
Hello Naffcat, (hehe funny...) ;)

Here is a VBScript that uses WMI to start and stop a service.

'Start Service
strServiceName = "Alerter"
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery ("Select * from Win32_Service Where Name ='" & strServiceName & "'")
For Each objService in colListOfServices
objService.StartService()
Next


'Stop Service
strServiceName = "Alerter"
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery("Select * from Win32_Service Where Name ='" & strServiceName & "'")
For Each objService in colListOfServices
objService.StopService()
Next

[8D] Keep cool... [8D]
Answered 02/04/2005 by: brenthunter2005
Fifth Degree Brown Belt

Please log in to comment
1
Thanks (again) Brent!
Answered 02/04/2005 by: Naffcat
Senior Purple Belt

Please log in to comment
1
Love it, that's a keeper. you should submit that to the script center
you can win free software!


'Start Service
strServiceName = "Alerter"
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery ("Select * from Win32_Service Where Name ='" & strServiceName & "'")
For Each objService in colListOfServices
objService.StartService()
Next


'Stop Service
strServiceName = "Alerter"
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery("Select * from Win32_Service Where Name ='" & strServiceName & "'")
For Each objService in colListOfServices
objService.StopService()
Next
Answered 02/04/2005 by: aogilmor
Ninth Degree Black Belt

Please log in to comment
1
[8D]

I would if I could, but I can't so I won't.

But then again you could always go to the Microsoft Script Center and download these yourselves.

[8D] Keep learning... [8D]
Answered 02/07/2005 by: brenthunter2005
Fifth Degree Brown Belt

Please log in to comment
1
I need VB script to stop and start multiple services. Please suggest the code
Answered 07/10/2008 by: nrkres
Senior Yellow Belt

Please log in to comment
1
How about using this new search engine thingy I keep hearing about? Is it called Poodle or something like that?

Come on...the idea of forums like this is, you do a bit of work for yourself and, when you hit a problem, ask for help. If you want someone to do the work for you, may I respectfully suggest that you try rent-a-coder.com.
Answered 07/10/2008 by: VBScab
Red Belt

Please log in to comment
1
google.com

scriptomatic download site:microsoft.com

win32_service is the class you want to use. scriptomatic will generate code for you.

let us know how it goes!
Answered 07/10/2008 by: aogilmor
Ninth Degree Black Belt

Please log in to comment
1
you know what the really sad thing is vb? look up further in the thread (which is very old).

the code is already there!! nrkres was too lazy to look at the script already provided! OMG, as the young folks are wont to say.
Answered 07/10/2008 by: aogilmor
Ninth Degree Black Belt

Please log in to comment
1
OMG! How did I miss that?!? Priceless...
Answered 07/11/2008 by: VBScab
Red Belt

Please log in to comment
1
Totally....
your "poodle" joke was good, too, thanks for that.

Bet you could have further confused him by telling him that poodle can be accessed via start/search on any xp workstation (he'd see the little microsoft search doggie) ;-)
Answered 07/11/2008 by: aogilmor
Ninth Degree Black Belt

Please log in to comment
1
Thinking around that point, I'd be rivetted to read his explanation of what a Wizard is :)
Answered 07/11/2008 by: VBScab
Red Belt

Please log in to comment
1
This version perhaps not better, but certainly more verbose (in code and messages displayed):

Service.wsf :
<job>
<runtime>
<description>Start or stop a Windows Service.</description>
<unnamed
name = "{start | stop}"
helpstring = "Action to take."
type = "string"
required = "true"
/>
<unnamed
name = "ServiceName"
helpstring = "Service to start or stop."
type = "string"
required = "true"
/>
<named
name = "nowait"
helpstring = "Do not wait for service to start or stop."
type = "simple"
required = "false"
/>
<example>Example: Service.wsf start MSSQLSERVER</example>
</runtime>
<script language="VBScript">

option explicit
dim StartStop, StartedStopped, WantStarted, DesiredState, Result
dim ServiceName, ServiceDescr

' validate arguments
if WScript.Arguments.Unnamed.Count <> 2 then
WScript.Arguments.ShowUsage
WScript.Quit
end if
StartStop = LCase(WScript.Arguments.Unnamed(0))
ServiceName = WScript.Arguments.Unnamed(1)
select case StartStop
case "start"
StartStop = "Start"
StartedStopped = "started"
WantStarted = true
DesiredState = "Running"
case "stop"
StartStop = "Stop"
StartedStopped = "stopped"
WantStarted = false
DesiredState = "Stopped"
case else
WScript.Arguments.ShowUsage
WScript.Quit
end select

dim WshShell, objWMIService, listOfServices, objService, WaitFor

' get the service object
set WshShell = WScript.CreateObject("WScript.Shell")
set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
set listOfServices = objWMIService.ExecQuery("select * from Win32_Service where Name = '" & ServiceName & "'")

if listOfServices.Count = 0 then

WshShell.Popup "Service '" & ServiceName & "' not found." _
,, "Service Not Found", 48 'Exclamation

else for each objService in listOfServices

ServiceDescr = "The " & objService.DisplayName & " service"

if objService.Started = WantStarted then

WshShell.Popup ServiceDescr & " is already " & LCase(DesiredState) & "." _
,, "Service Already " & DesiredState, 64 'Information

else

' start or stop
if WantStarted then
Result = objService.StartService()
else
Result = objService.StopService()
end if

' display success or failure message
select case Result
case 0
if not WScript.Arguments.Named.Exists("nowait") then
WaitFor = 60000 '60 seconds
while WaitFor > 0
WScript.Sleep(500) : WaitFor = WaitFor - 500 '0.5 seconds
set objService = objWMIService.Get("Win32_Service.Name='" & ServiceName & "'")
if objService.State = DesiredState then
WshShell.Popup ServiceDescr & " was " & StartedStopped & " successfully." _
,, "Service " & DesiredState, 64
WScript.Quit
end if
wend
end if
set objService = objWMIService.Get("Win32_Service.Name='" & ServiceName & "'")
WshShell.Popup "The " & objService.DisplayName & _
" service is in state " & objService.State & "." _
,, "Service Status", 64
case 3
WshShell.Popup "The " & objService.DisplayName & _
" can't be stopped because dependant services are running." _
,, "Cannot Stop Service", 48
case else
WshShell.Popup "Return value: " & Result & _
", " & objService.DisplayName & _
" is in state " & objService.State & "." _
,, "Cannot " & StartStop & " Service", 48
end select

end if

next end if

</script>
</job>


ICO files for shortcuts in the attached ZIP file (assuming it survives whatever forum attachment filters might be in place) - rename from txt to zip.

Attachment

Answered 12/03/2009 by: MarktheC
Yellow Belt

Please log in to comment
1
I got one, too. Works for me on 32bit and 64 bit systems...

Stop a service:

Option Explicit
On Error Resume Next
Public Sub StartApplication(App, WindowStyle)
dim aShell
set aShell= CreateObject("WScript.Shell")
aShell.Run App,WindowStyle
set ashell=nothing
end sub

StartApplication "%SYSTEMROOT%\system32\sc.exe stop YOUR SERVICE HERE",0
on error goto 0



Delete a service:

Option Explicit
On Error Resume Next
Public Sub StartApplication(App, WindowStyle)
dim aShell
set aShell= CreateObject("WScript.Shell")
aShell.Run App,WindowStyle
set ashell=nothing
end sub

StartApplication "%SYSTEMROOT%\system32\sc.exe delete YOUR SERVICE HERE",0
on error goto 0



Cheers
Answered 12/15/2009 by: McRip
Orange Senior Belt

Please log in to comment
1
Whilst there's no question that using SC works, your script is far too simplistic to be of any real value. I'd go as far as to say that it doesn't even really qualify as VBScript (which the OP requested): it's a glorified batch file. What happens if, say, a start fails in your script? How would anyone know, other than when it's too late? Error-trap, error-trap, error-trap...assume EVERYTHING will fail and code accordingly.
Answered 12/15/2009 by: VBScab
Red Belt

Please log in to comment
1
I can only say: It never failed.
Just try it before posting any reply...


Cheers
Answered 12/15/2009 by: McRip
Orange Senior Belt

Please log in to comment
1
I don't need to try it to see that it would work. There was no malice intended in my response, BTW. My point is, there's no handling for unexpected results. But then, as we all know, nothing unexpected ever happens with computers, so my fears are completely groundless. I'll go back to my nap.
Answered 12/15/2009 by: VBScab
Red Belt

Please log in to comment
1
I am not sure if I am missing something here put I am seeing to much complexity in other people's answers. This works:

option explicit
Dim objShell
set objShell = WScript.CreateObject("WScript.Shell")
objShell.run("net stop ""symantec antivirus""")
objShell.run("net stop defwatch")
objShell.run("net stop ""next service etc""")
Answered 06/03/2010 by: Xenon6
Yellow Belt

Please log in to comment
1
The complexity is there out of good coding practise, like error-trapping. Your script, like some of the others posted, assumes everything always works. Good luck with that approach...
Answered 06/03/2010 by: VBScab
Red Belt

Please log in to comment
1
Please forgive my ignorance as I am just starting to learn VB Scripting, but I think I have a bit of a problem. I am trying to stop a service, do a few other actions, then restart a service. I would like to use the code that Brenthunter2005 provided, but the service that I am trying to stop and then start at a later time is winmgmt. Is there any other way around using a script similar to this without using winmgmt as I believe it would prevent the script from running properly? I will use something like what Xenon6 recommended if I have to, but I am hoping not to. In the past when I have been manually stopping the winmgmt, I have been having errors doing so on some machine and I have to run "net stop winmgmt" multiple times before I am successful.

I hope what I'm trying to say isn't too confusing.
Answered 06/24/2011 by: gregredic
Yellow Belt

Please log in to comment
1
What are the "other actions" that require stopping and restarting WMI?
Answered 06/25/2011 by: VBScab
Red Belt

Please log in to comment
1
My ultimate goal is to fix machines with broken WMI. I am trying to do this on several thousand machines, so a script of some sort seems to be in order. I want to stop the winmgmt service, rename C:\Windows\System32\wbem\Repository to Repository_bad, start the winmgmt service, run 4 more lines of command:

cd /d %windir%\system32\wbem

for %i in (*.dll) do RegSvr32 -s %i

for %i in (*.exe) do %i /RegServer

gpupdate /Force /Boot

Then I need to initiate a repair on Configuration Manager, and finally run another script that I already have that corrects problems with SCCM.
Answered 06/27/2011 by: gregredic
Yellow Belt

Please log in to comment
1
Using McRip's code of:

Option Explicit
On Error Resume Next
Public Sub StartApplication(App, WindowStyle)
dim aShell
set aShell= CreateObject("WScript.Shell")
aShell.Run App,WindowStyle
set ashell=nothing
end sub

StartApplication "%SYSTEMROOT%\system32\sc.exe stop winmgmt",0
on error goto 0

Seems to stop the service just fine and when I change the stop to start within the script, it starts the service just fine. I think this might be what I have to use to stop and start the winmgmt service. I am trying to use the following script to then rename the Respository folder, but it doesn't seem to work on that folder, but will work on things not inside the system32 folder. Am I overlooking something here, or will it not allow me to rename this folder since it is in the system32 folder? The script is below:

Option Explicit
Dim strStartFolder
Dim oNamesDict
strStartFolder = "c:\Windows\System32\wbem"
Set oNamesDict = CreateObject("Scripting.Dictionary")
oNamesDict.Add "repository", "Repositorybad"
RenameSubFolders strStartFolder, oNamesDict
Set oNamesDict = Nothing
Sub RenameSubFolders(strFolder, oNames)
Dim oFSO:Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim oFolder
For Each oFolder In oFSO.GetFolder(strFolder).SubFolders
If oNames.Exists(UCASE(oFolder.Name))Then
WScript.Echo "Renaming " & oFolder.Path & " to " & ofolder.ParentFolder.Path & "\" & oNames.Item(UCase(oFolder.Name))
oFolder.Name = oNames.Item(UCase(oFolder.Name))
End If
RenameSubFolders oFolder.Path, oNames
Next
Set oFolder = Nothing
Set oFSO = Nothing
End Sub
Answered 06/27/2011 by: gregredic
Yellow Belt

Please log in to comment
1
Should that not be... If oNamesDict.Exists(UCASE(oFolder.Name))Then
WScript.Echo "Renaming " & oFolder.Path & " to " & ofolder.ParentFolder.Path & "\" & oNamesDict.Item(UCase(oFolder.Name))
oFolder.Name = oNamesDict.Item(UCase(oFolder.Name))
End If
RenameSubFolders oFolder.Path, oNamesDict
where 'oNames' should be 'oNamesDict'?

Also, note the use of the CODE tag in my post. You should use this tag when posting code or any other lengthy text here on AppDeploy. It makes post much easier to read and follow.

EDIT:
Look what I found...'// =========================================================================================================
'// Name: ControlServiceWMI
'// Purpose: Controls services using WMI
'// Input: strComputer - String - the computer on which we want to control the service. Null means local machine
'// strService - String - the name of the service. If blank, the function will use strDisplayName
'// strDisplayName - String - the display name of the service. If blank, the function will use strService
'// strOperation - String - the operation for the service: START, STOP, PAUSE or CONTINUE
'// intWaitTime - Integer - nbr of times to loop (effectively, the nbr of seconds to wait
'// for 'strOperation' to complete
'// Output: strError - String - contains error text, if operation fails
'// Returns: True/False
'// =========================================================================================================
Function ControlServiceWMI(ByVal strComputer, ByVal strService, ByVal strDisplayName, ByVal strOperation, ByVal intWaitTime, ByRef strError)

'// Define WMI *state* constants these are for the 'State' property
Const WMI_SERVICE_STOPPED = "Stopped"
Const WMI_SERVICE_STARTED = "Running"
Const WMI_SERVICE_START_PENDING = "Start Pending"
Const WMI_SERVICE_STOP_PENDING = "Stop Pending"
Const WMI_SERVICE_RUNNING = "Running"
Const WMI_SERVICE_CONTINUE_PENDING = "Continue Pending"
Const WMI_SERVICE_PAUSE_PENDING = "Pause Pending"
Const WMI_SERVICE_PAUSED = "Paused"
Const WMI_SERVICE_ERROR = "Unknown"

'// Define WMI *status* constants these are for the 'Status' property
Const WMI_SERVICE_OK = "OK"
Const WMI_SERVICE_DEGRADED = "Degraded"
Const WMI_SERVICE_UNKNOWN = "Unknown"
Const WMI_SERVICE_PRED_FAIL = "Pred Fail"
Const WMI_SERVICE_STARTING = "Starting"
Const WMI_SERVICE_STOPPING = "Stopping"
Const WMI_SERVICE_SERVICE = "Service" '// ?

'// Define string constants for service methods
Const START_SERVICE = "START"
Const STOP_SERVICE = "STOP"
Const PAUSE_SERVICE = "PAUSE"
Const CONTINUE_SERVICE = "CONTINUE"
Const SET_AUTOMATIC = "AUTOMATIC"
Const SET_MANUAL = "MANUAL"
Const SET_DISABLED = "DISABLED"

'// Win32_Service Method Return Value Table
Const WMI_Success = 0
Const WMI_NotSupported = 1
Const WMI_AccessDenied = 2
Const WMI_DependentServicesRunning = 3
Const WMI_InvalidServiceControl = 4
Const WMI_ServiceCannotAcceptControl = 5
Const WMI_ServiceNotActive = 6
Const WMI_ServiceRequestTimeout = 7
Const WMI_UnknownFailure = 8
Const WMI_PathNotFound = 9
Const WMI_ServiceAlreadyRunning = 10
Const WMI_ServiceDatabaseLocked = 11
Const WMI_ServiceDependencyDeleted = 12
Const WMI_ServiceDependencyFailure = 13
Const WMI_ServiceDisabled = 14
Const WMI_ServiceLogonFailure = 15
Const WMI_ServiceMarkedForDeletion = 16
Const WMI_ServiceNoThread = 17
Const WMI_StatusCircularDependency = 18
Const WMI_StatusDuplicateName = 19
Const WMI_StatusInvalidName = 20
Const WMI_StatusInvalidParameter = 21
Const WMI_StatusInvalidServiceAccount = 22
Const WMI_StatusServiceExists = 23
Const WMI_ServiceAlreadyPaused = 24

'// Build an array of the possible return values
Dim strWMI_ReturnErrors
Dim arrWMI_ReturnErrors

strWMI_ReturnErrors = ""
strWMI_ReturnErrors = strWMI_ReturnErrors & "Success,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Not Supported,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Access Denied,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Dependent Services Running,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Invalid Service Control,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Service Cannot Accept Control,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Service Not Active,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Service Request Timeout,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Unknown Failure,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Path Not Found,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Service Already Running,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Service Database Locked,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Service Dependency Deleted,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Service Dependency Failure,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Service Disabled,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Service Logon Failure,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Service Marked For Deletion,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Service No Thread,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Status Circular Dependency,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Status Duplicate Name,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Status Invalid Name,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Status Invalid Parameter,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Status Invalid Service Account,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Status Service Exists,"
strWMI_ReturnErrors = strWMI_ReturnErrors & "Service Already Paused"

'// Just in case you left the trailing comma in place...
If Left(strWMI_ReturnErrors, 1) = "," Then
strWMI_ReturnErrors = Left(strWMI_ReturnErrors, Len(strWMI_ReturnErrors) - 1)
End If

arrWMI_ReturnErrors = Split(strWMI_ReturnErrors, ",")

Dim strQuery
Dim objComputer
Dim objServiceList
Dim objService
Dim intCounter
Dim blnServiceReturn

ControlServiceWMI = False

If Len(strService) = 0 And Len(strDisplayName) = 0 Then
strMsgText = ""
strMsgText = strMsgText & "Neither the service name or service display name were specified."
Exit Function
End If

On Error Resume Next

'// Get WMI objects and initial variables
'Set objComputer = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set objComputer = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")

If Err.Number = 0 Then
'// Only interested in controllable services (i.e. not system services, drivers, etc)
'// (well, we would be if ANY service set its 'AcceptStop' flag...)
strQuery = ""
strQuery = strQuery & "Select * From Win32_Service"
strQuery = strQuery & " Where "

If Len(strService) > 0 Then
strQuery = strQuery & "Name = '" & strService & "'"
If Len(strDisplayName) > 0 Then
strQuery = strQuery & " And "
strQuery = strQuery & "DisplayName = '" & strDisplayName & "'"
End If
Else
strQuery = strQuery & "DisplayName = '" & strDisplayName & "'"
End If

'strQuery = strQuery & " And "
'strQuery = strQuery & "AcceptStop = True"

Set objServiceList = objComputer.ExecQuery (strQuery)

If Err.Number = 0 Then
If objServiceList.Count > 0 Then
For Each objService in objServiceList
'// Determine the operation and carry it out
With objService
Select Case (strOperation)
Case SET_AUTOMATIC
If (.StartMode <> SET_AUTOMATIC) Then
Err.Number = .ChangeStartMode("Automatic")
If Err.Number <> 0 Then
Do
If .State = WMI_SERVICE_STARTED Then
Exit Do
End If
Call Sleep(1)
intCounter = intCounter + 1
Loop Until intCounter = intWaitTime '// We're only going to wait intWaitTime seconds
End If
End If

Case SET_MANUAL
If (.StartMode <> SET_MANUAL) Then
Err.Number = .ChangeStartMode("Manual")
If Err.Number <> 0 Then
Do
If .State = WMI_SERVICE_STARTED Then
Exit Do
End If
Call Sleep(1)
intCounter = intCounter + 1
Loop Until intCounter = intWaitTime '// We're only going to wait intWaitTime seconds
End If
End If

Case SET_DISABLED
If (.StartMode <> SET_DISABLED) Then
Err.Number = .ChangeStartMode("Disabled")
If Err.Number <> 0 Then
Do
If .State = WMI_SERVICE_STARTED Then
Exit Do
End If
Call Sleep(1)
intCounter = intCounter + 1
Loop Until intCounter = intWaitTime '// We're only going to wait intWaitTime seconds
End If
End If

Case START_SERVICE
If (.State = WMI_SERVICE_STOPPED) Then
Err.Number = .StartService()
If Err.Number <> 0 Then
Do
If .State = WMI_SERVICE_STARTED Then
Exit Do
End If
Call Sleep(1)
intCounter = intCounter + 1
Loop Until intCounter = intWaitTime '// We're only going to wait intWaitTime seconds
End If
End If

Case STOP_SERVICE
If (.State = WMI_SERVICE_RUNNING) Or (.State = WMI_SERVICE_PAUSED) Then
Err.Number = .StopService()
If Err.Number <> 0 Then
Do
If .State = WMI_SERVICE_STOPPED Then
Exit Do
End If
Call Sleep(1)
intCounter = intCounter + 1
Loop Until intCounter = intWaitTime '// We're only going to wait intWaitTime seconds
End If
End If

Case PAUSE_SERVICE
If (.State = WMI_SERVICE_RUNNING) Then
Err.Number = .PauseService()
If Err.Number <> 0 Then
Do
If .State = WMI_SERVICE_PAUSED Then
Exit Do
End If
Call Sleep(1)
intCounter = intCounter + 1
Loop Until intCounter = intWaitTime '// We're only going to wait intWaitTime seconds
End If
End If

Case CONTINUE_SERVICE
If (.State = WMI_SERVICE_PAUSED) Then
Err.Number = .ContinueService()
If Err.Number <> 0 Then
Do
If .State = WMI_SERVICE_RUNNING Then
Exit Do
End If
Call Sleep(1)
intCounter = intCounter + 1
Loop Until intCounter = intWaitTime '// We're only going to wait intWaitTime seconds
End If
End If
End Select
End With
Next
Else
With Err
.Description = "The service name specified "
.Raise 999

If Len(strService) > 0 Then
If Len(strDisplayName) > 0 Then
.Description = .Description & "'" & strDisplayName & "'"
End If
Else
.Description = .Description & "=" & strService & "="
End If

.Description = .Description & " does not exist."
.Source = "ControlServiceWMI"
End With
End If
End If
End If

If Err.Number = 0 Then
ControlServiceWMI = True
Else
'// Loop through the error array and, when you hit what Err.Number is,
'// drop out and set the appropriate error text
For intCounter = 0 To UBound(arrWMI_ReturnErrors)
If Err.Number = intCounter Then
Err.Description = arrWMI_ReturnErrors(intCounter)
End If
Next

strMsgText = ""
strMsgText = strMsgText & "Error " & Err.Number & " occured."

If Len(Err.Description) > 0 Then
strMsgText = strMsgText & Err.Description
End If

strError = strMsgText
End If

On Error Goto 0

End Function

Sub Sleep(ByVal intDelayInSecs)
'// Sleep is here because, of course, one can't use WScript.Sleep in embedded VBS CAs
Dim datStart
Dim blnTimesUp

datStart = Now()
blnTimesUp = False

While Not blnTimesUp
If DateDiff("s", datStart, Now()) >= CInt(intDelayInSecs) Then
blnTimesUp = True
End If
Wend
End Sub
Answered 06/27/2011 by: VBScab
Red Belt

Please log in to comment
1
Set objParms = Wscript.Arguments

strServiceName = "WSRM"

If objParms.Count > 0 Then

Select Case UCase(objParms(0))

Case "START"

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery ("Select * from Win32_Service Where Name ='" & strServiceName & "'")
For Each objService in colListOfServices
objService.StartService()
Next
varToUser = MsgBox("WSRM Started.",vbInformation,"WSRM Service Stopper")

Case "STOP"

Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colListOfServices = objWMIService.ExecQuery("Select * from Win32_Service Where Name ='" & strServiceName & "'")
For Each objService in colListOfServices
objService.StopService()
Next
varToUser = MsgBox("WSRM Stopped.",vbInformation,"WSRM Service Stopper")
Case Else

varToUser = MsgBox("Invalid Parameter: " & objParms(0),vbExclamation,"WSRM Service Stopper")

End Select
Else
varToUser = MsgBox("Usage: [scriptname] [START | STOP]",vbInformation,"WSRM Service Stopper")

End If
Answered 08/03/2011 by: Pudnik
Yellow Belt

Please log in to comment
Answer this question or Comment on this question for clarity