Skip to content

Instantly share code, notes, and snippets.

@ynkdir
Created February 4, 2011 11:33
Show Gist options
  • Save ynkdir/811014 to your computer and use it in GitHub Desktop.
Save ynkdir/811014 to your computer and use it in GitHub Desktop.
zip.js
// WSH
function zip(zipfile, files) {
var fso = new ActiveXObject("Scripting.FileSystemObject");
var shell = new ActiveXObject("Shell.Application");
var process_id = get_process_id();
// create empty zip (right click -> new file -> compressed (zipped) folder)
var zip = fso.CreateTextFile(zipfile, true);
zip.Write("PK\5\6\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0");
zip.Close();
// copy to zip (drop files to zip folder)
var zipfolder = shell.NameSpace(fso.GetAbsolutePathName(zipfile));
for (var i = 0; i < files.length; ++i) {
var oldcount = thread_count(process_id);
var f = fso.GetFile(zipfile);
var oldsize = f.Size;
// FIXME: Second argument will not work. Cannot hide progress bar.
zipfolder.CopyHere(fso.GetAbsolutePathName(files[i]), 4 + 16);
// FIXME: Wait until finish. It seems that file size is updated
// when all items in the folder are finished, instead of for each
// item.
for (var j = 0; j < 10; ++j) {
if (oldsize != f.Size) {
break;
} else if (thread_count(process_id) > oldcount) {
// CopyHere threads are running. Wait it.
break;
}
WScript.Sleep(1000);
}
// Wait until CopyHere threads are finished.
while (thread_count(process_id) > oldcount) {
WScript.Sleep(1000);
}
// If file size is not changed, compression is probably cancelled.
if (oldsize == f.Size) {
return false;
}
}
return true;
}
function get_process_id()
{
var shell = WScript.CreateObject("WScript.Shell");
var p = shell.Exec("cmd.exe");
var wmi = GetObject("winmgmts://./root/cimv2");
var e = new Enumerator(wmi.ExecQuery("SELECT * FROM Win32_Process WHERE ProcessId = " + p.ProcessID));
var process_id = null;
for ( ; !e.atEnd(); e.moveNext()) {
var item = e.item();
process_id = item.ParentProcessId;
}
// Terminate() is slow.
p.StdIn.Close();
return process_id;
}
function thread_count(process_id)
{
var wmi = GetObject("winmgmts://./root/cimv2");
var res = wmi.ExecQuery("SELECT * FROM Win32_Thread WHERE ProcessHandle = " + process_id);
return res.Count;
}
function usage() {
WScript.Echo(
"usage: zip.js [options] zipfile file ...");
WScript.Quit(1);
}
function main() {
var args = WScript.Arguments;
var options = {
"args": []
};
for (var i = 0; i < args.length; ++i) {
if (args(i).match(/^(-r)$/)) {
// Ignore. Always recursive.
} else if (args(i).match(/^(-h|--help)$/)) {
usage();
} else {
options.args.push(args(i));
}
}
var zipfile = options.args.shift();
zip(zipfile, options.args);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment