Skip navigation

JSI Tip 0770. Using NETSVC in batch.

NETSVC.EXE is a tool to remotely start, stop, and query the status of services from the command line.

To use NETSVC, you need no special rights unless the owner of a computer has blocked out all users. To use the /stop or /start options, you must have an account on the target computer with privileges that allow starting or stopping services.

Because NETSVC uses the service names as listed under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services in the Registry, the service names displayed with NETSVC can be slightly different from those displayed with NET START.

The syntax is:

netsvc servicename \\computername switch

where

servicename is the name of the service you want to control. You can enter either the service names, as defined in the Registry, or the display names, as shown when you double-click the Services icon in Control Panel. If the service name has embedded spaces, place quotes around the service name.

\\computername is the name of the computer (local or remote) whose services you want to control.

switch is /query, /start, /stop, /continue, /list, or /pause. No servicename is required when you use the /list switch. All switches are case-insensitive.

Unfortuneatly, NETSVC does not return an ERRORLEVEL, making it difficult to test wether a service is running, stopped or paused.

I have written SVCSTAT.BAT to test the status of a service and return an ERRORLEVEL environment variable as follows:

0 - An error has occured, computername or servicename is invalid.
1- The service is running.
2- The service is stopped.
3- The service is paused.

The Syntax for calling SVCSTAT.BAT is:

call SVCSTAT \\ComputerName ServiceName

Example for testing the Schedule service on the local computer:

call SVCSTAT \\%ComputerName% Schedule
if %ERRORLEVEL% EQU 0 goto err
if %ERRORLEVEL% EQU 1 goto running
if %ERRORLEVEL% EQU 2 goto stopped ELSE goto paused

SVCSTAT.BAT contains:

@echo off
set ERRORLEVEL=0
if "%1"

"" goto end
if "%2"

"" goto end
for /f "Tokens=1-4" %%i in ('netsvc %2 %1 /query') do call :test "%%k"
goto end
:test
if %1

"running" set ERRORLEVEL=1&goto end
if %1

"stopped" set ERRORLEVEL=2&goto end
if %1=="paused" set ERRORLEVEL=3
:end
Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish