Wednesday, December 22, 2010

Create Batch File to Start or End Window Services

www.tech-recipes.com

The important commands are the following:
NET START – starts the service
NET STOP – ends the service

For example:

NET STOP "Error Reporting Service"

Output: The Error Reporting Service service was stopped successfully.

Knowing the commands, one can now easily create batch files called something like beforegame.bat and aftergame.bat.

Before.bat would contain all the NET STOP commands to end the nonessential services.
After.bat would be exactly the same except all the NET STOP commands would be replaced with NET START commands to restart all the common services.

A sample of the before.bat file might look something like this:

NET STOP "Error Reporting Service"
NET STOP "FTP Publishing Service"
SET STOP "IIS Admin"
NET STOP "Messenger"


Likewise, the after.bat file might look something like this:

NET START "Error Reporting Service"
NET START "FTP Publishing Service"
SET START "IIS Admin"
NET START "Messenger"

STOP SERVICES and FOR LOOPS in Batch files

www.tech-recipes.com


The key is to use delimaters...well, sorta. You want to trick the FOR loop into looking for delimiters.
~~ SERVICES.TXT ~~
; be sure to surround your values by QUOTES (")
"Apache Tomcat 4.1.31"
"Apache Tomcat 5.0.27"
"MySQL41"
; and with the EOL switch, lines beginning in ";" are ignored

~~ START.EM.UP.BAT ~~
FOR /F "eol=; tokens=1,2,3,4,5,6,7* delims= " %%a IN (SERVICES.TXT) DO NET STOP %%a %%b %%c %%d %%e %%f %%g

also notice a few things
    1. no quotes around filename
    2. the "%%x" variables have two % symbols (this is because i'm running inside of a BAT already.
    3. there are just as many "tokens" as there are "%%x" variables
    4. there is only a space after the delims= declaration

lastly, the resulting output:NET STOP "Apache Tomcat 4.1.31"
NET STOP "Apache Tomcat 5.0.27"
NET STOP "MySQL41"