What is Windows Service
Windows Service is a background process that performs certain task. We can perform various methods on service like start,stop,pause or resume on local or remote machine.
In this article you will perform Stop methods on windows service using VB.Net. Here you can use "StopService" Function which is given below. Using this function you can perform this action on local or remote machine according to your need.
Step-By-Step
Windows Service is a background process that performs certain task. We can perform various methods on service like start,stop,pause or resume on local or remote machine.
In this article you will perform Stop methods on windows service using VB.Net. Here you can use "StopService" Function which is given below. Using this function you can perform this action on local or remote machine according to your need.
Private Sub StopService(ByVal strComputer As String, ByVal strService As String)
Try
Dim objWMIService, colServiceList, objService, errReturn, objSWbemLocator
objSWbemLocator = CreateObject("WbemScripting.SWbemLocator")
If (strComputer = Environment.MachineName.ToString) Then
objWMIService = objSWbemLocator.ConnectServer(strComputer, "root\cimv2")
Else
objWMIService = objSWbemLocator.ConnectServer(strComputer, "root\cimv2", UserName, Password)
End If
objWMIService.Security_.ImpersonationLevel = 3
colServiceList = objWMIService.ExecQuery("Select * from Win32_Service where DisplayName='" & strService & "'")
For Each objService In colServiceList
errReturn = objService.StopService()
Next
If (errReturn = 0) Then
colServiceList = objWMIService.ExecQuery("Associators of " & "{Win32_Service.DisplayName='" & strService & "'} Where " & "AssocClass=Win32_DependentService " & "Role=Dependent")
For Each objService In colServiceList
objService.StopService()
Next
End If
MessageBox.Show("Service Successfully Stopped.", "Service Manager", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MessageBox.Show(ex.Message, "Service Manager", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Step-By-Step
- Create object for connecting server either local or remote.
- For Remote connection we use admin credential.
- Use WMI Win32_Service for selecting particular service on desired machine.
- Use For Loop for stopping that service.
- Next step will be for stopping dependent services.
- Here you have Successfully done.