Click here to Skip to main content
15,900,725 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I want to retrieve windows services from remote machine having startup type as Automatic. But unfortunately, ServiceController class does not return 'Startup Type'. Hence I've tried to retrieve these services with the help of WMI.

string filter = "SELECT * FROM Win32_Service WHERE StartMode = 'Auto'";  
ObjectQuery objQuery = new ObjectQuery(filter);  
ManagementObjectSearcher mgmtObjSearcher = new ManagementObjectSearcher(objQuery);  
ManagementObjectCollection returnCollection = mgmtObjSearcher.Get();


For local machine, it went smoothly & I got all automatic services in object 'returnCollection'.

Now, I want to perform same operation for remote machine. I have all the necessary rights to retrieve services from remote machine. But I don't know how to format WMI query to do that.

I have written following code:

string serverName = "xyz";
  
//Connection credentials to the remote computer -   
ConnectionOptions connOptions = new ConnectionOptions();  
//connOptions.Username = "username";  
//connOptions.Password = "password";  
  
System.Management.ManagementScope mgmtScope = new System.Management.ManagementScope("\\\\" + serverName, connOptions);  
 
string filter = "SELECT * FROM Win32_Service WHERE StartMode = 'Auto'";  
ObjectQuery objQuery = new ObjectQuery(filter);  
ManagementObjectSearcher mgmtObjSearcher = new ManagementObjectSearcher(mgmtScope, objQuery);  
ManagementObjectCollection returnCollection = mgmtObjSearcher.Get();


Please help me to format the WMI query. TIA.

Regards,
Pranav
Posted

1 solution

Hi,


I've done something like this in the past...

You should use something like this function:

Private Sub GetServicesInfo()
      Dim ServObj As ServiceObject = Nothing
      Try
          ' Create a new ManagementClass object binded to the Win32_Service WMI class
          Dim mcServices As New ManagementClass("\\" & Me.MachineName & "\root\cimv2:Win32_Service")

          ' Loop through each service
          For Each moService As ManagementObject In mcServices.GetInstances()


              Dim PropList As New Dictionary(Of String, String)
              Dim test As PropertyDataCollection = mcServices.Properties
              For Each prop As PropertyData In test
                  Dim value As String
                  Try
                      value = moService.GetPropertyValue(prop.Name).ToString()
                  Catch ex As Exception
                      value = ""
                  End Try
                  PropList.Add(prop.Name, value)
              Next
              ServObj = New ServiceObject(Me, PropList("Name"))
              With ServObj
                  .DisplayName = PropList("Caption")
                  .Status = PropList("State")
                  .Path = PropList("PathName")
                  .StartUp = PropList("StartMode")
                  .Description = PropList("Description")
                  ' .Name = PropList("Name")
              End With

              If Not ServiceObjects.ContainsKey(ServObj.DisplayName) Then
                  ServiceObjects.Add(ServObj.DisplayName, ServObj)
              End If

          Next
      Catch ex As Exception
          MsgBox("Error retrieving services check the access rights." + vbCrLf + GetErrorInfo(ex))
      End Try

  End Sub



A Class has been added which I use to manage services, hope you like it!

ServiceManagementController.vb

Imports System.Collections.Generic
Imports System.ServiceProcess
Imports System.Management
Imports System.Runtime.InteropServices


''' <summary>
''' ServiceManagementController is an object that will control/display/manage Services
''' </summary>
''' <remarks></remarks>
Public Class ServiceManagementController

#Region "Values for Services"

    <dllimport("advapi32.dll",> Public Shared Function OpenSCManager(ByVal sMachineName As String, ByVal sDbName As String, ByVal iAccess As Integer) As IntPtr
    End Function
    <dllimport("advapi32.dll",> Public Shared Function CreateService(ByVal hSCM As IntPtr, ByVal sName As String, ByVal sDisplay As String, ByVal iAccess As Integer, ByVal iServiceType As Integer, ByVal iStartType As Integer, ByVal iError As Integer, ByVal sPath As String, ByVal sGroup As String, ByVal iTag As Integer, ByVal sDepends As String, ByVal sUser As String, ByVal sPass As String) As IntPtr
    End Function
    <dllimport("advapi32.dll",> Public Shared Function CloseServiceHandle(ByVal iHandle As IntPtr) As Integer
    End Function
    <dllimport("advapi32.dll",> Public Shared Function OpenService(ByVal hSCM As IntPtr, ByVal sServiceName As String, ByVal iDesiredAccess As Integer) As IntPtr
    End Function
    <dllimport("advapi32.dll",> Public Shared Function DeleteService(ByVal hService As IntPtr) As Boolean
    End Function

    Private Enum ServiceControlManagerEnum
        Connect = &H1
        CreateService = &H2
        EnumerateService = &H4
        Lock = &H8
        QueryLockStatus = &H10
        ModifyBootConfig = &H20
        AllAccess = (StandardRightsRequired Or Connect Or ServiceControlManagerEnum.CreateService Or EnumerateService Or ServiceControlManagerEnum.Lock Or QueryLockStatus Or ModifyBootConfig)
        StandardRightsRequired = &HF0000
    End Enum
    Private Enum ServiceAccessTypeEnum
        QueryConfig = &H1
        ChangeConfig = &H2
        QueryStatus = &H4
        EnumerateDependents = &H8
        Start = &H10
        [Stop] = &H20
        PauseContinue = &H40
        Interrogate = &H80
        UserDefinedControl = &H100
        AllAccess = (StandardRightsRequired Or QueryConfig Or ChangeConfig Or QueryStatus Or EnumerateDependents Or Start Or [Stop] Or PauseContinue Or Interrogate Or UserDefinedControl)
        StandardRightsRequired = &HF0000
    End Enum
    Private Enum ServiceTypeEnum
        Win32OwnProcess = &H10
        AutoStart = &H2
        ErrorNormal = &H1
    End Enum
    Private Enum ServiceControlTypeEnum
        OwnProcess = &H10
        ShareProcess = &H20
        KernelDriver = &H1
        FileSystemDriver = &H2
        InteractiveProcess = &H100
    End Enum
    Private Const c_sBefore As String = "<ideaconfiguration><group><name>Global</name><batlist uselist="" no="" />"
    Private Const c_sAfter As String = "</group></ideaconfiguration>"

#End Region

#Region "Properties"
    Private exceptioncaught As Integer
    ''' <summary>
    ''' Sorted Dictionary of all services on selected machine
    ''' </summary>
    ''' <remarks>Service DisplayName, ServiceObject</remarks>
    Private dicServiceObjects As New SortedDictionary(Of String, ServiceObject)
    Public Property ServiceObjects() As SortedDictionary(Of String, ServiceObject)
        Get
            Return dicServiceObjects
        End Get
        Set(ByVal value As SortedDictionary(Of String, ServiceObject))
            dicServiceObjects = value
        End Set
    End Property

    Private strMachineName As String
    Public Property MachineName() As String
        Get
            Return strMachineName
        End Get
        Set(ByVal value As String)
            strMachineName = value
        End Set
    End Property

#End Region

#Region "Constructor"

    Public Sub New(ByVal MachineName As String)
        Me.MachineName = MachineName
        GetServicesInfo()
    End Sub

#End Region

#Region "Private Methods"


    Private Sub GetServicesInfo()
        Dim ServObj As ServiceObject = Nothing
        Try
            ' Create a new ManagementClass object binded to the Win32_Service WMI class
            Dim mcServices As New ManagementClass("\\" & Me.MachineName & "\root\cimv2:Win32_Service")

            ' Loop through each service
            For Each moService As ManagementObject In mcServices.GetInstances()


                Dim PropList As New Dictionary(Of String, String)
                Dim test As PropertyDataCollection = mcServices.Properties
                For Each prop As PropertyData In test
                    Dim value As String
                    Try
                        value = moService.GetPropertyValue(prop.Name).ToString()
                    Catch ex As Exception
                        value = ""
                    End Try
                    PropList.Add(prop.Name, value)
                Next
                ServObj = New ServiceObject(Me, PropList("Name"))
                With ServObj
                    .DisplayName = PropList("Caption")
                    .Status = PropList("State")
                    .Path = PropList("PathName")
                    .StartUp = PropList("StartMode")
                    .Description = PropList("Description")
                    ' .Name = PropList("Name")
                End With

                If Not ServiceObjects.ContainsKey(ServObj.DisplayName) Then
                    ServiceObjects.Add(ServObj.DisplayName, ServObj)
                End If

            Next
        Catch ex As Exception
            MsgBox("Error retrieving services check the access rights." + vbCrLf + GetErrorInfo(ex))
        End Try

    End Sub

    Public Function InstallService(ByVal ServiceName As String, ByVal displayName As String, ByVal PathtoExecutable As String, Optional ByVal UserName As String = Nothing, Optional ByVal password As String = Nothing, Optional ByVal StartService As Boolean = True) As Boolean
        Try

            'Dim sUserID As String = sDomainName & "\" & sUserID
            'Dim sPassword As String = sPassword
            'put nothing if System account needed
            If IsServiceInstalled(ServiceName) Then _
               UninstallService(ServiceName)

            ' INSTALL
            Dim hSCM As IntPtr = OpenSCManager(Me.MachineName, Nothing, _
               ServiceControlManagerEnum.AllAccess)
            If hSCM.ToInt32 = 0 Then
                MsgBox("Could not install service. [1]")
                Return False
            Else
                Dim iServiceType As Integer = ServiceTypeEnum.Win32OwnProcess

                Dim hService As IntPtr = CreateService(hSCM, ServiceName, _
                   ServiceName, ServiceControlManagerEnum.AllAccess, _
                      iServiceType, ServiceTypeEnum.AutoStart, _
                      ServiceTypeEnum.ErrorNormal, PathtoExecutable, Nothing, Nothing, _
                      Nothing, UserName, password)
                If hService.ToInt32 = 0 Then
                    MsgBox("Could not install service. [2]")
                    Return False
                Else
                    CloseServiceHandle(hService)
                End If

                CloseServiceHandle(hSCM)

                If StartService = True Then
                    Call ControlServices(ServiceName, "Start")
                End If

            End If
            Return True
        Catch ex As Exception
            MsgBox("Error occured while trying to install service : " + ServiceName + GetErrorInfo(ex))
        End Try
    End Function

    Public Function UninstallService(ByVal ServiceName As String) As Boolean

        If IsServiceInstalled(ServiceName) Then
            ' STOP SERVICE
            Call ControlServices(ServiceName, "Stop")
        Else
            Return False
            Exit Function
        End If

        Dim hSCM As IntPtr = OpenSCManager(Me.MachineName, Nothing, ServiceControlManagerEnum.AllAccess)
        If hSCM.ToInt32 = 0 Then
            MsgBox("Could not delete service. [1]")
            Return False
        Else
            Dim hService As IntPtr = OpenService(hSCM, ServiceName, ServiceAccessTypeEnum.AllAccess)
            If hService.ToInt32 = 0 Then
                ' TODO: FAILED
                MsgBox("Unable to Delete Service : " + ServiceName)
                Return False
            Else
                If Not DeleteService(hService) Then
                    MsgBox("Could not delete service. [2]")
                    Return False
                End If

                CloseServiceHandle(hService)
            End If

            CloseServiceHandle(hSCM)
        End If
        Return True
    End Function

    Private Function IsServiceInstalled(ByVal sServiceName As String) As Boolean
        Dim bResult As Boolean = False

        Dim oServiceArray() As ServiceProcess.ServiceController
        oServiceArray = ServiceProcess.ServiceController.GetServices(Me.MachineName)

        For Each oServiceController As ServiceProcess.ServiceController In oServiceArray
            If oServiceController.ServiceName.Trim.ToUpper = sServiceName.Trim.ToUpper Then
                Dim i As New ServiceControllerPermissionAttribute(Security.Permissions.SecurityAction.Demand)
                Dim d As New ServiceControllerPermission
                Try
                    If Security.Permissions.ResourcePermissionBase.Any Then
                        d.ToString()
                    End If
                Catch
                End Try
                bResult = True
                Exit For
            End If
        Next

        Return bResult
    End Function

    Private Function CheckStatusOfService(ByVal ServiceName As String, ByVal MachineName As String) As Boolean
        Dim Status As Boolean = False
        Dim objWinServ As New ServiceController
        objWinServ.ServiceName = ServiceName
        objWinServ.MachineName = MachineName

        'If the service is stopped then the button to start it needs to be enabled
        If objWinServ.Status = ServiceControllerStatus.Stopped Then
            Status = True
        End If

        Return Status
    End Function


    Private Sub ControlServices(ByVal ServiceName As String, ByVal sTask As String)
        Dim Status As String = ""
        Dim objWinServ As New ServiceController
        Dim sServiceName As String = ServiceName

        objWinServ.MachineName = Me.MachineName

        objWinServ.ServiceName = sServiceName

        Try

            Select Case sTask

                Case "Reset"
                    If objWinServ.Status = ServiceControllerStatus.Running Then
                        'Service is currently running, so you will have to stop it before starting it
                        'First stop all it's child services, then stop the service itself
                        Call CheckForChildServices(sServiceName, "Stop")
                    End If

                    If objWinServ.Status = ServiceControllerStatus.Stopped Then 'This is satisfied if the service was running and then was stopped by code or if it was already stopped
                        'service is already stopped so just start it...so first start all it's parent services
                        Call CheckForParentServices(sServiceName, "Start")
                        ServiceStart(objWinServ.DisplayName)
                    End If

                Case "Start"
                    If objWinServ.Status = ServiceControllerStatus.Stopped Then 'This is satisfied if the service was running and then was stopped by code or if it was already stopped
                        Call CheckForParentServices(sServiceName, "Start")
                        If Not exceptioncaught = 0 Then
                            MsgBox("Could not Start " & objWinServ.DisplayName)
                            exceptioncaught = 0
                        End If
                    End If

                Case "Stop"
                    If objWinServ.Status <> ServiceControllerStatus.Stopped Then
                        Call CheckForChildServices(sServiceName, "Stop")
                        If Not exceptioncaught = 0 Then
                            MsgBox("Could not Stop " & objWinServ.DisplayName)
                            exceptioncaught = 0
                        End If
                    End If
                Case "Pause"
                    If objWinServ.Status = ServiceControllerStatus.Paused Then
                        Call CheckForParentServices(sServiceName, "Start")
                    Else
                        Call CheckForChildServices(sServiceName, "Pause")
                        'ServicePause()
                    End If

            End Select
        Catch ex As System.InvalidOperationException
            MsgBox("Service does not exist" + vbCrLf + GetErrorInfo(ex))
            Exit Sub
        Catch e As Exception
            MsgBox(GetErrorInfo(e))
            Exit Sub
        End Try
    End Sub

    Private Sub CheckForParentServices(ByVal ServiceName As String, ByVal NextService As String)
        Dim objService As New ServiceController
        objService.ServiceName = ServiceName
        objService.MachineName = Me.MachineName

        Dim objParentService As ServiceController

        For Each objParentService In objService.ServicesDependedOn
            CheckForParentServices(objParentService.DisplayName, NextService)
        Next
        If NextService = "Start" Then
            Call ServiceStart(ServiceName)
        ElseIf NextService = "Pause" Then
            Call ServicePause(ServiceName)
        End If

    End Sub

    Private Sub CheckForChildServices(ByVal ServiceName As String, ByVal NextService As String)
        Dim objService As New ServiceController
        objService.ServiceName = ServiceName
        objService.MachineName = Me.MachineName
        Dim objChildService As ServiceController

        For Each objChildService In objService.DependentServices
            CheckForChildServices(objChildService.DisplayName, NextService)
        Next

        If NextService = "Stop" Then
            Call ServiceStop(ServiceName)
        ElseIf NextService = "Pause" Then
            Call ServicePause(ServiceName)
        Else
            Call ContinueService(ServiceName)
        End If

    End Sub

    Private Function ServiceStart(Optional ByVal ServiceName As String = "") As Boolean
        Dim objService As New ServiceController
        objService.MachineName = Me.MachineName
     
            objService.ServiceName = ServiceName



        If objService.Status = ServiceControllerStatus.Stopped Then
            Try
                objService.Start()
                objService.WaitForStatus(ServiceControllerStatus.Running, System.TimeSpan.FromSeconds(20))
            Catch ex As TimeoutException
                MsgBox("Could not Start " & ServiceName & " - TimeOut expired" & GetErrorInfo(ex))
                Return False
            Catch e As Exception
                MsgBox("Could not Start " & ServiceName & GetErrorInfo(e))
                Return False
            End Try
        ElseIf objService.Status = ServiceControllerStatus.Paused Then
            Call ContinueService(objService.ServiceName)
        End If
        Return True
    End Function

    Private Function ServiceStop(Optional ByVal ServiceName As String = "") As Boolean
        Dim objService As New ServiceController
        objService.MachineName = Me.MachineName
        objService.ServiceName = ServiceName

        If objService.Status = ServiceControllerStatus.Running Then
            Try
                objService.Stop()
                objService.WaitForStatus(ServiceControllerStatus.Stopped, System.TimeSpan.FromSeconds(20))
            Catch ex As TimeoutException
                MsgBox("Could not Stop " & ServiceName & " - TimeOut expired" & GetErrorInfo(ex))
                Return False
            Catch e As Exception
                MsgBox("Could not Stop " & ServiceName & GetErrorInfo(e))
                Return False
            End Try
        End If
        Return True
    End Function

    Private Function ServicePause(ByVal ServiceName As String) As Boolean
        Dim objService As New ServiceController
        objService.MachineName = Me.MachineName
        objService.ServiceName = ServiceName

        If objService.Status = ServiceControllerStatus.Paused Then
            Try
                objService.Continue()
                objService.WaitForStatus(ServiceControllerStatus.Running, System.TimeSpan.FromSeconds(20))
            Catch ex As TimeoutException
                MsgBox("Could not change status from Paused To Continue for " & ServiceName & " - TimeOut expired" + GetErrorInfo(ex))
                Return False
            Catch e As Exception
                MsgBox("Could not change status from Paused To Continue for " & ServiceName & " - " + GetErrorInfo(e))
                Return False
            End Try
        ElseIf objService.Status = ServiceControllerStatus.Stopped Then
            Call ControlServices(ServiceName, "Start")
        ElseIf objService.Status = ServiceControllerStatus.Running Then
            Try
                objService.Pause()
                objService.WaitForStatus(ServiceControllerStatus.Paused, System.TimeSpan.FromSeconds(20))
            Catch ex As TimeoutException
                MsgBox("Could not change status from Running To Paused for " & ServiceName & " - TimeOut expired" + GetErrorInfo(ex))
                Return False
            Catch e As Exception
                MsgBox("Could not change status from Running To Paused for " & ServiceName & " - " + GetErrorInfo(e))
                Return False
            End Try

        End If
        Return True
    End Function

    Private Sub ContinueService(ByVal ServiceName As String)
        Dim objService As New ServiceController
        objService.ServiceName = ServiceName
        objService.MachineName = Me.MachineName
        If objService.Status = ServiceControllerStatus.Paused Then
            Try
                objService.[Continue]()
                objService.WaitForStatus(ServiceControllerStatus.Running, System.TimeSpan.FromSeconds(20))
            Catch ex As TimeoutException

                Console.WriteLine("Could not change status from Paused To Continue for " & ServiceName & " - TimeOut expired")
            Catch e As Exception

                Console.WriteLine("Could not change status from Paused To Continue for " & ServiceName & " - " & e.Message)
            End Try
        End If

        If objService.Status = ServiceControllerStatus.Stopped Then
            Call ServiceStop(ServiceName)
        End If

    End Sub
#End Region

#Region "Public Methods"
    Public Sub StartService(ByVal ServiceName As String)
        Me.ControlServices(ServiceName, "Start")
    End Sub

    Public Sub StopService(ByVal ServiceName As String)
        Me.ControlServices(ServiceName, "Stop")
    End Sub

    Public Sub PauseService(ByVal ServiceName As String)
        Me.ControlServices(ServiceName, "Pause")
    End Sub

    Public Sub RestartService(ByVal ServiceName As String)
        Me.ControlServices(ServiceName, "Reset")
    End Sub
#End Region

#Region "ServiceObject"

    ''' <summary>
    ''' Service Object is used to store all information about a specific service
    ''' </summary>
    ''' <remarks></remarks>
    Public Class ServiceObject
        Private exceptioncaught As Integer
        Private objWinServ As New ServiceController

        Public Sub New(ByVal ParentObject As ServiceManagementController, ByVal ServiceName As String)
            Me.Parent = ParentObject
            Me.Name = ServiceName
            objWinServ.MachineName = Me.Parent.MachineName
            objWinServ.ServiceName = Me.Name
        End Sub

#Region "Properties"

        Private objParent As ServiceManagementController
        Public Property Parent() As ServiceManagementController
            Get
                Return objParent
            End Get
            Set(ByVal value As ServiceManagementController)
                objParent = value
            End Set
        End Property

        Private strName As String
        Public Property Name() As String
            Get
                Return strName
            End Get
            Set(ByVal value As String)
                strName = value
            End Set
        End Property

        Private strDisplayName As String
        Public Property DisplayName() As String
            Get
                Return strDisplayName
            End Get
            Set(ByVal value As String)
                strDisplayName = value
            End Set
        End Property

        Private strDescription As String
        Public Property Description() As String
            Get
                Return strDescription
            End Get
            Set(ByVal value As String)
                strDescription = value
            End Set
        End Property

        Private strPath As String
        Public Property Path() As String
            Get
                Return strPath
            End Get
            Set(ByVal value As String)
                strPath = value
            End Set
        End Property

        Private strStartUp As String
        Public Property StartUp() As String
            Get
                Return strStartUp
            End Get
            Set(ByVal value As String)
                strStartUp = value
            End Set
        End Property

        Private strStatus As String
        Public Property Status() As String
            Get
                Return strStatus
            End Get
            Set(ByVal value As String)
                strStatus = value
            End Set
        End Property

#End Region

#Region "Public Methods"

        Public Sub StartService()
            Me.ControlServices("Start")
        End Sub

        Public Sub StopService()
            Me.ControlServices("Stop")
        End Sub

        Public Sub PauseService()
            Me.ControlServices("Pause")
        End Sub

        Public Sub RestartService()
            Me.ControlServices("Reset")
        End Sub

        Public Sub ChangeStartupMode(ByVal StartUp As String)
            Try

                Dim path As String = "\\" & Me.Parent.MachineName & "\root\cimv2:Win32_Service.Name='" & Me.Name & "'"
                Dim p As New ManagementPath(path)
                'construct the management object
                Dim ManagementObj As New ManagementObject(p)
                'we will use the invokeMethod method of the ManagementObject class
                Dim parameters As Object() = New Object(0) {}
                parameters(0) = StartUp
                ManagementObj.InvokeMethod("ChangeStartMode", parameters)
            Catch ex As Exception
                MsgBox("Error occured while trying to set StartUp Mode" + vbCrLf + "Check if you have the necessary access rights!" + GetErrorInfo(ex))
            End Try
        
          
        End Sub



#End Region

#Region "Private Methods"

        Private Sub ControlServices(ByVal sTask As String)
            Dim Status As String = ""
            'Dim objWinServ As New ServiceController
            Dim sServiceName As String = Me.Name

            'objWinServ.MachineName = Me.Parent.MachineName

            'objWinServ.ServiceName = sServiceName

            Try

                Select Case sTask

                    Case "Reset"
                        If objWinServ.Status = ServiceControllerStatus.Running Then
                            'Service is currently running, so you will have to stop it before starting it
                            'First stop all it's child services, then stop the service itself
                            Call CheckForChildServices(sServiceName, "Stop")
                        End If

                        If objWinServ.Status = ServiceControllerStatus.Stopped Then 'This is satisfied if the service was running and then was stopped by code or if it was already stopped
                            'service is already stopped so just start it...so first start all it's parent services
                            Call CheckForParentServices(sServiceName, "Start")
                            ' ServiceStart(objWinServ.ServiceName)
                        End If

                    Case "Start"
                        If objWinServ.Status = ServiceControllerStatus.Stopped Then 'This is satisfied if the service was running and then was stopped by code or if it was already stopped
                            Call CheckForParentServices(sServiceName, "Start")
                            If Not exceptioncaught = 0 Then
                                MsgBox("Could not Start " & objWinServ.DisplayName)
                                exceptioncaught = 0
                            End If
                        End If

                    Case "Stop"
                        If objWinServ.Status <> ServiceControllerStatus.Stopped Then
                            Call CheckForChildServices(sServiceName, "Stop")
                            If Not exceptioncaught = 0 Then
                                MsgBox("Could not Stop " & objWinServ.DisplayName)
                                exceptioncaught = 0
                            End If
                        End If
                    Case "Pause"
                        If objWinServ.Status = ServiceControllerStatus.Paused Then
                            Call CheckForParentServices(sServiceName, "Start")
                        Else
                            Call CheckForChildServices(sServiceName, "Pause")
                            'ServicePause()
                        End If

                End Select
            Catch ex As System.InvalidOperationException
                MsgBox("Service does not exist" + vbCrLf + GetErrorInfo(ex))
                Exit Sub
            Catch e As Exception
                MsgBox(GetErrorInfo(e))
                Exit Sub
            End Try
        End Sub

        Private Function ServiceStart(Optional ByVal ServiceName As String = "") As Boolean
            'Dim objService As New ServiceController
            'objService.MachineName = Me.Parent.MachineName
            If ServiceName = "" Then
                objWinServ.ServiceName = Me.Name
            Else
                objWinServ.ServiceName = ServiceName
            End If


            If objWinServ.Status = ServiceControllerStatus.Stopped Then
                Try
                    objWinServ.Start()
                    objWinServ.WaitForStatus(ServiceControllerStatus.Running, System.TimeSpan.FromSeconds(20))
                Catch ex As TimeoutException
                    MsgBox("Could not Start " & Me.Name & " - TimeOut expired" & GetErrorInfo(ex))
                    Return False
                Catch e As Exception
                    MsgBox("Could not Start " & Me.Name & GetErrorInfo(e))
                    Return False
                End Try
            ElseIf objWinServ.Status = ServiceControllerStatus.Paused Then
                Call ContinueService(objWinServ.ServiceName)
            End If
            Return True
        End Function

        Private Function ServiceStop(Optional ByVal ServiceName As String = "") As Boolean
            ' Dim objService As New ServiceController
            '  objService.MachineName = Me.Parent.MachineName
            If ServiceName = "" Then
                objWinServ.ServiceName = Me.Name
            Else
                objWinServ.ServiceName = ServiceName
            End If


            If objWinServ.Status = ServiceControllerStatus.Running Then
                Try
                    objWinServ.Stop()
                    objWinServ.WaitForStatus(ServiceControllerStatus.Stopped, System.TimeSpan.FromSeconds(20))

                Catch ex As TimeoutException
                    MsgBox("Could not Stop " & Me.Name & " - TimeOut expired" & GetErrorInfo(ex))
                    Return False
                Catch e As Exception
                    MsgBox("Could not Stop " & Me.Name & GetErrorInfo(e))
                    Return False
                End Try
            End If
            Return True
        End Function

        Private Function ServicePause() As Boolean
            'Dim objService As New ServiceController
            '  objService.MachineName = Me.Parent.MachineName
            ' objService.ServiceName = Me.Name

            If objWinServ.Status = ServiceControllerStatus.Paused Then
                Try
                    objWinServ.Continue()
                    objWinServ.WaitForStatus(ServiceControllerStatus.Running, System.TimeSpan.FromSeconds(20))
                Catch ex As TimeoutException
                    MsgBox("Could not change status from Paused To Continue for " & Me.Name & " - TimeOut expired" + GetErrorInfo(ex))
                    Return False
                Catch e As Exception
                    MsgBox("Could not change status from Paused To Continue for " & Me.Name & " - " + GetErrorInfo(e))
                    Return False
                End Try
            ElseIf objWinServ.Status = ServiceControllerStatus.Stopped Then
                Call ControlServices("Start")
            ElseIf objWinServ.Status = ServiceControllerStatus.Running Then
                Try
                    objWinServ.Pause()
                    objWinServ.WaitForStatus(ServiceControllerStatus.Paused, System.TimeSpan.FromSeconds(20))
                Catch ex As TimeoutException
                    MsgBox("Could not change status from Running To Paused for " & Me.Name & " - TimeOut expired" + GetErrorInfo(ex))
                    Return False
                Catch e As Exception
                    MsgBox("Could not change status from Running To Paused for " & Me.Name & " - " + GetErrorInfo(e))
                    Return False
                End Try

            End If
            Return True
        End Function

        Private Sub CheckForParentServices(ByVal sServiceName As String, ByVal NextService As String)
            '  Dim objService As New ServiceController
            objWinServ.ServiceName = sServiceName
            ' objService.MachineName = Me.Parent.MachineName

            Dim objParentService As ServiceController

            For Each objParentService In objWinServ.ServicesDependedOn
                CheckForParentServices(objParentService.DisplayName, NextService)
            Next
            If NextService = "Start" Then
                Call ServiceStart()
            ElseIf NextService = "Pause" Then
                Call ServicePause()
            End If

        End Sub

        Private Sub CheckForChildServices(ByVal sServiceName As String, ByVal NextService As String)
            'Dim objService As New ServiceController
            objWinServ.ServiceName = sServiceName
            'objService.MachineName = Me.Parent.MachineName
            Dim objChildService As ServiceController

            For Each objChildService In objWinServ.DependentServices
                CheckForChildServices(objChildService.DisplayName, NextService)
            Next

            If NextService = "Stop" Then
                Call ServiceStop()
            ElseIf NextService = "Pause" Then
                Call ServicePause()
            Else
                Call ContinueService(sServiceName)
            End If

        End Sub

        Private Sub ContinueService(ByVal sServiceName As String)
            '   Dim objService As New ServiceController
            objWinServ.ServiceName = sServiceName
            'objWinServ.MachineName = Me.Parent.MachineName
            If objWinServ.Status = ServiceControllerStatus.Paused Then
                Try
                    objWinServ.[Continue]()
                    objWinServ.WaitForStatus(ServiceControllerStatus.Running, System.TimeSpan.FromSeconds(20))
                Catch ex As TimeoutException

                    Console.WriteLine("Could not change status from Paused To Continue for " & sServiceName & " - TimeOut expired")
                Catch e As Exception

                    Console.WriteLine("Could not change status from Paused To Continue for " & sServiceName & " - " & e.Message)
                End Try
            End If

            If objWinServ.Status = ServiceControllerStatus.Stopped Then
                Call ServiceStop(sServiceName)
            End If

        End Sub

        

#End Region
    End Class

#End Region


End Class



Good luck!

K.

 
Share this answer
 
v2
Comments
The Cyclone 7-Jul-10 0:28am    
Reason for my vote of 5
Thank you!
Kraeven 8-Jul-10 10:49am    
You're welcome...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900