Wednesday, October 24, 2007

Don't use bat files anymore: Automate your MS Windows tasks using JScript

Being a Unix geek I am quite used to automating my routine system administration tasks using cronjobs. When it comes to Microsoft Windows there is of course the equivalent tool called Scheduled Tasks. Sure enough we can create a bat file to put our little scripts together, call them from our Scheduled Task and we have a similar automation to cronjobs. However there is one annoying side effect: In the middle of your work an ugly cmd-terminal-window-thing pops up, spits some text and disappears before you can read even a word. It is simply your bat file run by the scheduled tasks tool and its output.

I wanted to find a better way of doing this and, I have spent a bit of time googling about Windows Scripting and JScript. I wanted to use JScript because (putting it quite crudely) it is Microsoft version of Javascript, which I know much better than VB. I used to write VB (Basic more like) in the past, but thats another story.

Turns out it is quite easy. I used a Microsoft specific object WScript to run my tasks and the rest was basically Javascript.

Running A Command:

First you need to instantiate an ActiveXObject of WScript.Shell:
var shell = new ActiveXObject("WScript.Shell");
Then you can run commands like this:
shell.Run("yourcmd", 0);
The second argument to Run method makes sure to not display the 'ugly' command window while running our little shell command.

Print Debugging:

It is inevitable that you will need to check your scripts problems unless it is a very simple short one. I am sure there are quite elegant ways of debugging your script (you might need something like Visual Studio for this, I am not sure) nevertheless a few 'print' statements here and there can be very effective as well. Unfortunately there is no straight print command in JScript but this does the job as good as print:
WScript.Echo("Hello!");
Just save your script with a .js extension and you are in business.

0 comments:

Post a Comment