Pesky tasks with batch scripts

Scripting is art. Nifty and subtle, wicked cool scripts can weave magic, and startle compiled language supporters with their skimpy appearance. But it is for getting yet-another-pesky-job done, that scripting becomes so important.
The batch scripting language, is the Windows equivalent(read wannabe) for the more sane bash scripting. Like many other products from Microsoft, it lacks elegance, is limited and does not have a good support for regular expressions. Below are some pesky jobs that can still be done with batch scripts.

Pesky job 1 : Map a network drive

net use N:| find “OK”
if errorlevel 1 net use N: \servernamepath$ ******** /user:******* /persistent:yes

This will check if the drive N is mapped or not; in case there is an error, it will map servernamepath with proper username/password values and keep this map persistent across reboots.

Pesky job 2 : Copying files with a time stamp
Say we want to copy a few files from one directory to another file to another with the current date stamp, it could be a simple
copy help.txt Desktop%date:~10,4%%date:~7,2%%date:~4,2%-chgs-1.txt

Truly ugly? Quite right.

Normally the date command would output

C:Documents and SettingsTatha>date
The current date is: Mon 11/17/2008
Enter the new date: (mm-dd-yy)

To use the date-stamp say in an echo statement, put the command with in percentage signs. to extract part of the time stamp, the command should be followed with a “:~offset, number_of_characters”. For example

C:Documents and SettingsTatha>echo %date:~0,14%
Mon 11/17/2008

So, the copy command above would create a copy the help.txt to the path C:Documents and SettingsTathaDesktop with a name 20081711-chgs-1.txt, on 17th November 2008.

But wait, this wont work in a Windows NT box. Seems like the automatic variables DATE and TIME were not implemented until windows 2000, so if you want a time stamp in an NT box you should

time /t >> file.txt

Pesky job 3 : Starting and stopping windows services gracefully
Another glitch when running newer bat scripts in Windows NT, that I came across is controlling Windows services. Consider the following snippet to stop a service named SomeAppServer or someappserver in a Windows Xp box.

net start | find “SomeAppServer”
if errorlevel 1 goto STOPPED
if errorlevel 0 echo %date% %time% Attempting to Stop SomeAppServer >> log.txt
start /wait net stop “SomeAppServer” >> log.txt 2>&1
if errorlevel 1 echo %date% %time% SomeAppServer could not be stopped >>log.txt
echo %date% %time% SomeAppServer is stopped >> log.txt
echo — >> log.txt

However, in case the name of the service is someappserver, instead of SomeAppServer as written in the script, it would fail to stop the service in a Windows NT box. NT treats the service names as case sensitive and you need to supply exactly as it is listed.

Here are some good resources for batch scripting

Leave a Reply

Your email address will not be published. Required fields are marked *