Check Service Status

OSVBNET 1,391 Reputation points
2021-05-14T02:40:23.047+00:00

Hello everyone,
I need to check if a service is (a. disabled/enabled) and (b. running/stopped)?

Now I start a process and send this command "SC query wsearch" and read the response but:

  1. It does not return both of the above, just one!
  2. I search for a string inside the response, like Response.Contains("STATE : 1 STOPPED") which is not a safe way and does not work sometimes!

Is there a safer way to check the Service Status and Startup Type in VB.NET ? Thanks :)

Developer technologies VB
{count} votes

Accepted answer
  1. Karen Payne MVP 35,586 Reputation points Volunteer Moderator
    2021-05-14T14:19:43.66+00:00

    Here is what would give you a service status if you can upgrade to an newer .NET Framework version.

    Option Infer On
    Imports System.ServiceProcess
    
    Public Class WindowsServices
        Public Function GetStatus(pServiceName As String) As String
            Dim status = "Not installed"
    
            ' Get our service, if not found in GetServices then it's not installed
            Dim sc = ServiceController.GetServices().
                    FirstOrDefault(Function(serviceController) serviceController.ServiceName = pServiceName)
    
            If sc Is Nothing Then
                Return status
            End If
    
            Select Case sc.Status
                Case ServiceControllerStatus.Running
                    status = "Running"
                Case ServiceControllerStatus.Stopped
                    status = "Stopped"
                Case ServiceControllerStatus.Paused
                    status = "Paused"
                Case ServiceControllerStatus.StopPending
                    status = "Stopping"
                Case ServiceControllerStatus.StartPending
                    status = "Starting"
                Case Else
                    status = "Status Changing"
            End Select
    
            Return status
    
        End Function
    
    End Class
    

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.