Anybody who had to write WSH scripts knows about this annoying problem.
If you want to run your script from command line you need to write something like
cscript myfile.js
Which is ugly and too much typing compared to simple
myfile
that you only need to type if you use the lowly CMD batch file language.
Even worse when you double click on a .js file it is by default executed
using wscript (windowed host) even if the script itself was intended to
run from command line. There is a way to specify what host to use for a
particular script but doing it requires to create yet another file.
Which makes using WSH scripts messy and untidy.
Since I really like the
power scripts have compared to batch file language I couldn't rest
until I
found a solution to this problem. In
fact there are two solutions. The second
one shown here I invented it on my own a few months ago
but it looks so obvious that I wouldn't be surprised if somebody did it
long before. After I published it here a
Usenet poster Pavel A. suggested another
solution in a private e-mail. I like it
more than my original one so with his
permission I'll put it here first. Note that
both solutions work for JScript. I don't use
VBScript and have no idea whether it is possible to use something similar with
it. If not this is one more reason for you to switch to JScript instead ;-)
Solution 1
Your code will reside in a single file with .cmd extension.
Let's call it myscript.cmd. Create an empty file with this name and put the following
in the beginning
@if (1 == 0) @end /*
@cscript.exe /E:jscript /nologo "%~f0" "%~dp0" %*
@goto :eof
*/
Now put your JScript code after the */.
That's all. Now you can run your script by typing myscript or by double-clicking it.
Note that the header is completely generic so you can reuse it verbatim in any
script you write.
Solution 2
This solution is very similar but
uses a different trick. Create a .cmd file and put the following
in the beginning
@echo off
setlocal
set MYSELF=%~dpnx0
set JSFILE="%MYSELF%.js"
echo /* > %JSFILE%
type "%MYSELF%" >> %JSFILE%
cscript //nologo %JSFILE% "%MYSELF%"
del %JSFILE%
exit /B 0
*/
Now put your JScript code after the */.
Note that this sample doesn't support command line parameters for the script.
Passing them is trivial and is left as an exercise for the reader.