Monthly Archives: October 2009

How to Check whether a Windows Service is running or not by passing the service name

Here is the awesome VB.Net code to check whether the windows service is running or not by passing the service name:

Instructions:

  • Open a New Console application
  • Add a new bas module called modMain
  • Set a reference to System.ServiceProcess (Go to Project > Add Reference and select System.ServiceProcess under .Net tab and click OK.)
  • Copy the following code to modMain bas module
Module modMain
  Sub Main()
    If IsServiceRunning("Print Spooler") Then
      Console.WriteLine("Print Spooler Service Running in this machine." & vbCrLf)
    Else
      Console.WriteLine("Print Spooler Service not running in this machine; or the service doesn't exists.\n" & vbCrLf)
    End If
    Console.WriteLine("Hit Enter to exit.")
    Console.Read()
  End Sub
  Function IsServiceRunning(ByVal sServiceName As String) As Boolean
    Try
      Dim myServiceController As ServiceProcess.ServiceController
      myServiceController = New ServiceProcess.ServiceController(sServiceName)
      Return myServiceController.Status = ServiceProcess.ServiceControllerStatus.Running
    Catch ex As Exception
      Console.WriteLine(ex.ToString)
      Return False
    End Try
  End Function
End Module

Project Type: Console
Language: VB.Net
Tested with: VS 2008

Incoming search terms: