Link to home
Start Free TrialLog in
Avatar of folletxavier
folletxavier

asked on

Start/Stop Windows Service

How can I Start/Stop Windows Service using VB?
/Xavier
ASKER CERTIFIED SOLUTION
Avatar of TimCottee
TimCottee
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Sorry, forgot to add the comments, you can skip the Sub Main that is irrelevant to you. You can supply either an empty string or a valid server name to control/query the service on a local or remote machine.
How 'bout

Shell "cmd.exe /c net start ServiceName"

or

Shell "cmd.exe /c net stop ServiceName"


Wher ServiceName is the name of the service you wish to toggle.
You can use variables in the above too:


Dim SrvName

SrvName="ServiceName"


Shell "cmd.exe /c net stop " & SrvName

or

Shell "cmd.exe /c net start " & SrvName
If the above is something you may consider using, it can also be run hidden using:


RetVal = Shell("cmd.exe /c net start " & SrvName, vbHide)
Actually, you don't need to include the "cmd /c" (in my last post)

RetVal = Shell("net stop " & SrvName, vbHide)
Avatar of Corvax021899
Corvax021899

Or you could use the ADSI function...
1- Make a Reference to Active DS Type Library in VB

Make a Module Like This:

Public function Stop_NT_Service(ServiceName as string,ComputerName as String)

Dim oServer As IADsComputer
Dim oServiceOp As IADsServiceOperations

Set oServer = GetObject("WinNT://" & ComputerName)
Set oServiceOp = oServer.GetObject("Service", ServiceName)

If oServiceOp.status = ADS_SERVICE_RUNNING Then oServiceOp.Stop
End Function

Public function Start_NT_Service(ServiceName as string,ComputerName as String)

Dim oServer As IADsComputer
Dim oServiceOp As IADsServiceOperations

Set oServer = GetObject("WinNT://" & ComputerName)
Set oServiceOp = oServer.GetObject("Service", ServiceName)

If Not oServiceOp.status = ADS_SERVICE_RUNNING Then oServiceOp.Start

End Function



Avatar of folletxavier

ASKER

czpczp:
I really like you code, simple and working... But TimCottee's let me be in better control.
Thank you all!
/Xavier
very nice piece of code TimCottee, thanks

j