1

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

2
  • Do you mean "bash" or "batch" for one of the tags? Dec 16, 2009 at 18:30
  • I removed the "bash" tag, there's no bash going on here.
    – Bill Weiss
    Dec 16, 2009 at 19:23

3 Answers 3

3

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
                                (STOPPABLE,PAUSABLE,ACCEPTS_SHUTDOWN)
        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{     (($_.name -eq $service) -or ($_.displayname -eq $service))
}

    if (result -eq $null)
    {
        Do something if service does not exist
    }
    else
    {
        Do something if service does exist
    }
}
2

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
        objService.StartService()
    End If
Next
Set colServices = Nothing

Hope this helps.

2

If you need pure batch, you can use sc query <service_name> to check for your service. If the service does not exist it throws an error. You can check for the error code 1060 with if errorlevel 1060. I use something similar in an install script to check for another service that is a dependency.

REM throw output away with > nul
sc query MyServer > nul
IF ERRORLEVEL 1060 (
    echo "Service is not installed"
) else (
    rem do something else
)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .