Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How would you check is a service exists and if so do some operation?

share|improve this question
Do you mean "bash" or "batch" for one of the tags? – Dennis Williamson Dec 16 '09 at 18:30
I removed the "bash" tag, there's no bash going on here. – Bill Weiss Dec 16 '09 at 19:23

The sc command allows you to query a Windows service, the full details of this can be found here.

So you can query a particular service, if it exists, you will get details like the following:

sc query lanmanserver results in

SERVICE_NAME: lanmanserver
        TYPE               : 20  WIN32_SHARE_PROCESS
        STATE              : 4  RUNNING
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0

Querying a service that doesn't exist results in:

[SC] EnumQueryServicesStatus:OpenService FAILED 1060:

The specified service does not exist as an installed service.

So you can write a script to check for the response and then perform whatever action you want to based on that.

If you're not stuck on using batch scripting, you can also write something much nicer in Powershell, such as

function serviceCheck ($service, $machine) {

$result = [System.ServiceProcess.ServiceController]::GetServices($machine) | where{     (($ -eq $service) -or ($_.displayname -eq $service))

	if (result -eq $null)
		Do something if service does not exist
		Do something if service does exist
share|improve this answer

After a little googling, here's little vb snippet for testing if a service exist and execute the start method.

Dim colServices As Object
Dim objService As Object
Set colServices = GetObject("winmgmts:").ExecQuery _
    ("Select Name from Win32_Service where Name = '" & PutServiceNameHere& "'")
For Each objService In colServices
    If Len(objService.Name) Then
    End If
Set colServices = Nothing

Hope this helps.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.