The inimitable Raymond Chen of Old New Thing fame once wrote a blog post about using inappropriate tools for the job. It came to my mind the other day when I needed to do a timestamp-based conditional in a batch file. The underlying cause was rather vanilla - file H is generated from file X, so if file X was modified later than H was, the batch needs to rebuild H.
When I saw this post regarding timestamps in batch files, and many similar ones elsewhere, I decided to break open a slightly more capable tire inflating tool. Specifically, JavaScript. Behold later.js:
var fso = new ActiveXObject("Scripting.FileSystemObject");
function LastModDate(n)
{
var fn = WScript.Arguments(n);
return fso.FileExists(fn) ?
new Date(fso.GetFile(fn).DateLastModified).valueOf()
: 0;
}
WScript.Quit(LastModDate(0) > LastModDate(1) ? 1 : 0);
With something like this, the batch file becomes trivial:
cscript //B later.js FileX.txt FileH.txt
if errorlevel 1 MyRebuild /from H /to X
As as added bonus, if file H doesn't exist, the script returns 1 so that it's rebuilt anyway.
This is poor man's makefile. But I didn't feel like bring a dependency on make into my process.
A note about the "new Date()" thing: the value of DateLastModified is not a valid JavaScript Date object. I presume it's a VARIANT of type VT_DATE; anyway, JavaScript doesn't know how to compare them, but you can build a proper Date around one.
No comments:
Post a Comment