@naimi/alib
Version:
1,204 lines (931 loc) • 35.8 kB
JavaScript
//!//////////////////////////////////////////////////////////////////////////////
//!
//! JScript alib.jse WSH by Alireza Naimi v1.0
//!
//! Bootstrap code for running a javascript app in windows. Run as:
//!
//! cscript.js app.js <appname> <app arguments> ...
//!
//!//////////////////////////////////////////////////////////////////////////////
;
js_engine = 1; //! 0: node, 1: JScript
//!--- add missing "include" functiosn
if (!Array.prototype.includes) {
Array.prototype.includes = function (key) {
for (var i = this.length; i--;)
if (key === this[i])
return true;
return false;
}
}
//!--- add missing "include" function for string
if (!String.prototype.includes) {
String.prototype.includes = function (str) {
return ((this.indexOf(str) !== -1) ? true : false);
}
}
if (!Array.prototype.includes_ali) {
Array.prototype.includes_ali = function (key, val) {
for (var i = this.length; i--;)
if (val === this[i][key])
return true;
return false;
}
}
//!--- replaceArray prototype
String.prototype.replaceArray = function (find, replace) {
var str_replace = this;
for (var i = 0; i < find.length; i++) {
str_replace = str_replace.replace(find[i], replace[i]);
}
return str_replace;
};
//!--- replace ch in string
String.prototype.replaceAt = function (index, replacement) {
return this.substr(0, index) + replacement + this.substr(index + replacement.length);
}
if (!Array.isArray) {
Array.isArray = function (arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
String.prototype.InArray = function (arr) {
for (var i = arr.length; i--;) {
if (arr[i] === String(this)) {
return true;
}
}
return false;
}
if (!Array.prototype.clean) {
Array.prototype.clean = function (deleteValue) {
for (var i = 0; i < this.length; i++) {
if (this[i] == deleteValue) {
this.splice(i, 1);
i--;
}
}
return this;
}
}
//!//////////////////////////////////////////////////////////////////////////////
//! Load script, and call app.main()
//!//////////////////////////////////////////////////////////////////////////////
var arguments = WScript.arguments;
if (arguments.length > 0) {
var args = [];
for (var i = 0; i < arguments.length; i++) {
args.push(WScript.arguments(i));
}
}
//!/////////////////////////////////////////////////////////////////////////////
//! Bootstrap code, basic module loading functionality
//!/////////////////////////////////////////////////////////////////////////////
//!---------------------------------- Ali ---------------------------
process = { //! process.stdout.write
stdout: {
write: function (s) {
WScript.StdOut.Write(s);
}
}
}
echo = prompt = function (s) {
WScript.echo(s);
//! WScript.StdOut.Write("\r" + s); // carriage return
};
print = log = function (s) {
if (s instanceof Object) {
try {
printObj(s, "");
} catch (e) {
echo("Error 101: " + e);
}
} else {
WScript.echo(s);
}
};
//! Define recursive function to print nested tree values
printObj = function (obj, prefix) {
var print_only_strings = true; // true: only strings, false: all strings, functions, properties...
for (var k in obj) {
if (obj[k] instanceof Object) {
var should_print = true
//! �?�?????????�???�???�???�???�???????�???????�???????�???????�???????????????????ͺ��ɸ����Ⱦ����̵�����������???????????????????�?��?�?�??????????
prefix2 = prefix + " ";
if (typeof (obj[k]) != "string" && print_only_strings) should_print = false
if (should_print) WScript.Echo(prefix + chr(9492) + k + "> ");
printObj(obj[k], prefix2);
} else {
WScript.Echo(prefix + chr(9500) + k + ":\t" + obj[k]);
//! typeof(obj[k])===string)
};
}
};
print = log = function (s) {
if (s instanceof Object) {
try {
printObj(s, "");
} catch (e) {
echo("Error 101: " + e);
}
} else {
WScript.echo(s);
}
};
printObj2 = function (obj) {
printObj(obj, "");
}
printf = function (s) {
WScript.StdOut.WriteLine(s)
}
printl = function (s) {
WScript.StdOut.Write(s)
}
scanf = function () {
scanf = LCase(WScript.StdIn.ReadLine)
}
// private void print_(StringBuilder buf, String prefix, String prefixChild) {
// buf.append(prefix);
// buf.append(id);
// buf.append('\n');
// for (Iterator<TreeNode> it = Nodes.iterator(); it.hasNext();) {
// TreeNode next = it.next();
// if (it.hasNext()) {
// next.print_(buf, prefixChild + "?? ", prefixChild + "? ");
// } else {
// next.print_(buf, prefixChild + "?? ", prefixChild + " ");
// }
// }
// }
asc = ascii = function (a) {
return a.charCodeAt(0);
}
chr = char = function (n) {
return String.fromCharCode(n);
}
printUTF = function (n) {
if (!n) n = 256;
for (i = 0; i < n; i++)
WScript.StdOut.Write(i + ": " + chr(i) + "\t")
}
exec = function (cmd, bEcho) {
//! run: separate window, slow | exec: faster same window
if (typeof bEcho == 'undefined') bEcho = true;
if (bEcho) WScript.Echo("> " + cmd);
var shell = WScript.CreateObject("WScript.Shell");
var p = shell.exec(cmd);
var output = [];
var stderr = [];
var line;
while (true) {
var n = 0;
while (!p.StdOut.AtEndOfStream) {
line = p.StdOut.ReadLine();
WScript.StdOut.WriteLine(line);
output.push(line);
n++;
}
while (!p.StdErr.AtEndOfStream) {
line = p.StdErr.ReadLine();
WScript.StdErr.WriteLine(line);
stderr.push(line);
n++;
}
if (n === 0)
break;
}
return [p.ExitCode, output, stderr];
};
guid = uuidv4 = function () {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0,
v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
exec_ = function (cmd, bEcho) {
if (typeof bEcho == 'undefined') bEcho = true;
if (bEcho) WScript.Echo(cmd);
var ret = sh.Exec(cmd).StdOut.ReadAll();
if (ret != "") {
return ret;
} else {
return "err0: " + ret;
}
}
cube = function (cmd, bEcho) {
// get length of json object:
// var key, n = 0; for(key in dic.Abbr) if(dic.Abbr.hasOwnProperty(key)) n++; // get length of object
// for (var i in vm.vm1) if (dic.Abbr.hasOwnProperty(i)) {
// WScript.Echo( i + " > " + dic.Abbr[i] );
// var re = new RegExp(i, "ig");
var pth = "@set p=c:/TotalCMD/usr/sci/civil/cube & @set PATH=%p%;%p2%;c:/TotalCMD/usr/sci/dev/vcs/Git/usr/share/cygwin;%PATH%"
}
run = function (strCmd, intWindowStyle, bWaitOnReturn, bEcho) {
//! run: separate window, slow | exec: faster same window
//! intWindowStyle Description
//! 0 Hides the window and activates another window.
//! 1 Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when displaying the window for the first time.
//! 2 Activates and minimized
//! 3 Activates and maximized
//! 4 Displays a window in its most recent size and position. The active window remains active.
//! 5 Activates the window and displays it in its current size and position.
//! 6 Minimizes the specified window and activates the next top-level window in the Z order.
//! 7 Displays the window as a minimized window. The active window remains active.
//! 8 Displays the window in its current state. The active window remains active.
//! 9 Activates and displays the window. If the window is minimized or maximized, the system restores it to its original size and position. An application should specify this flag when restoring a minimized window.
//! 10 Sets the show-state based on the state of the program that started the application.
//! bWaitOnReturn an option to either wait for the process to return or continue without it
//! set defaults
if (typeof bEcho == 'undefined') bEcho = true;
if (!intWindowStyle) intWindowStyle = 1;
if (typeof bWaitOnReturn == 'undefined') bWaitOnReturn = true;
//! run
if (bEcho) WScript.Echo(strCmd , " (bWaitOnReturn: " , bWaitOnReturn ? "true" : "false" , ")");
var _sh_ = new ActiveXObject('WScript.Shell');
var errorlevel = _sh_.Run(strCmd, intWindowStyle, bWaitOnReturn);
if (bEcho) WScript.Echo("return code: ", errorlevel);
_sh_ = null
return errorlevel;
}
get_folder_file_list = function (dir_name, ext_list) {
var ret = [];
var objFolder = fs.GetFolder(dir_name);
fc = new Enumerator(objFolder.files); //! colFiles
for (; !fc.atEnd(); fc.moveNext()) {
var itm = fc.item();
var ext = fs.GetExtensionName(itm.name).toLowerCase();
var match = false;
for (var i in ext_list) {
if (ext == ext_list[i].toLowerCase()) match = true;
if ("*" == ext_list[i]) match = true;
}
if (match) {
ret.push(itm);
}
}
return ret;
}
click = function (x, y, button) {
if (!button) button = "left";
exec_("nircmd setcursorwin " + x + " " + y);
exec_("nircmd sendmouse " + button + " click");
};
sendKey = SendKeys = press = function (str) {
//! Key Code
//! --------------------
//! { {{}
//! } {}}
//! [ {[}
//! ] {]}
//! ~ {~}
//! + {+}
//! ^ {^}
//! % {%}
//! BACKSPACE {BACKSPACE}, {BS}, or {BKSP}
//! BREAK {BREAK}
//! CAPS LOCK {CAPSLOCK}
//! DEL or DELETE {DELETE} or {DEL}
//! DOWN ARROW {DOWN}
//! END {END}
//! ENTER {ENTER} or ~
//! ESC {ESC}
//! F1 through F16 {F1} through {F16}
//! HELP {HELP}
//! HOME {HOME}
//! INS or INSERT {INSERT} or {INS}
//! LEFT ARROW {LEFT}
//! NUM LOCK {NUMLOCK}
//! PAGE DOWN {PGDN}
//! PAGE UP {PGUP}
//! PRINT SCREEN {PRTSC}
//! RIGHT ARROW {RIGHT}
//! SCROLL LOCK {SCROLLLOCK}
//! TAB {TAB}
//! UP ARROW {UP}
//! ---------------- prefixes:
//! Key Code
//! + SHIFT
//! ^ CTRL
//! % ALT
//! example: CTRL-ALT-DELETE : "^%{DELETE}"
wsh.SendKeys(str);
}
sleep = wait = function (ms) {
WScript.Sleep(ms)
}
timer = function (sec) {
while (sec > 0) {
WScript.StdOut.Write("\r" + sec--);
WScript.Sleep(1000);
}
}
timeout = function (sec) {
while (sec > 0) {
WScript.StdOut.Write("\rWaiting for " + sec-- + " seconds, press a key to continue ...");
WScript.Sleep(1000);
}
}
is64 = function () {
if (fs.FolderExists(wsh.ExpandEnvironmentStrings("%windir%") + "/sysnative"))
return true;
else
return false;
}
alert = MsgBox2 = function (str, nType, strTitle, nSecondsToWait) {
//! example: MsgBox2("Hi", vbCritical, "Title",3);
try {
if (!nSecondsToWait) nSecondsToWait = 0;
nType = nType == null ? vbInformation : nType;
if (!strTitle) strTitle = "Title";
intButton = wsh.Popup(str, nSecondsToWait, strTitle, nType)
return intButton;
switch (intButton) {
case ret_Yes:
WScript.Echo("Glad to hear you feel alright.");
break;
case ret_No:
WScript.Echo("Hope you're feeling better soon.");
break;
case ret_timeout:
WScript.Echo("Is there anybody out there?");
break;
}
} catch (e) {
echo("Error 102: " + e);
}
}
Include = function (jsFile) {
var fso, f, s;
fso = new ActiveXObject("Scripting.FileSystemObject");
f = fso.OpenTextFile(jsFile);
s = f.ReadAll();
f.Close();
eval(Include(jsFile));
return (s);
}
InputBox2 = function (str, tit) {
if (is64())
return InputBox(str, "Title");
else
return ("ss");
}
set2 = function (key, val) {
var objVarClass = GetObject("winmgmts://./root/cimv2:Win32_Environment")
var objStartup = objWMIService.Get("Win32_ProcessStartup")
var objVar = objVarClass.SpawnInstance_()
objVar.Name = key
objVar.VariableValue = val
objVar.UserName = "<System>"
objVar.Put_()
WScript.Echo("Created environment variable " + key)
}
set3 = function (key, val) {
strComputer = "."
objWMIService = GetObject("winmgmts:" + "{impersonationLevel=impersonate}!//" + strComputer + "/root/cimv2")
objStartup = objWMIService.Get("Win32_ProcessStartup")
objConfig = objStartup.SpawnInstance_()
objConfig.EnvironmentVariables = [key + "=" + val]
objProcess = GetObject("winmgmts:root/cimv2:Win32_Process")
intProcessID = 0
errReturn = objProcess.Create("cmd.exe /k set", null, objConfig, intProcessID)
}
set = function (key, val, level) {
if (!level) level = 2
oPrcEnv(key) = val; //! Stays for this process (safest)
if (level >= 2) oVolEnv(key) = val; //! Stays until log out of Windows
if (level >= 3) oUsrEnv(key) = val; //! Stays for this user
if (level >= 4) oSysEnv(key) = val; //! Stays for all users
}
setx = function (key, val) {
set(key, val, 4)
}
env2 = function (str) {
return sh.ExpandEnvironmentStrings(str)
}
print_env = function (lvl) {
if (!lvl) lvl = ["PROCESS", "USER", "VOLATILE", "SYSTEM"]
var WSHShell = new ActiveXObject("WScript.Shell");
for (var l in lvl) {
WScript.Echo("--------- " + lvl[l] + " ---------");
var Env = WSHShell.Environment(lvl[l]);
var s = "";
var colVars = new Enumerator(Env);
for (; !colVars.atEnd(); colVars.moveNext()) {
s += colVars.item() + "\n";
}
WScript.Echo(s);
}
}
getTasks = function (name) {
tasks = sh.Exec("tasklist /v /fo csv").StdOut.ReadAll().split(/\r?\n/)
ret = [];
for (var i in tasks) {
arr = tasks[i].split(/,(?=(?:(?:[^"]*"){2})*[^"]*$)/);
t = {
Name: arr[0].replace(/\"/g, ""),
PID: parseInt(arr[1].replace(/\"/g, "")),
Session: arr[2].replace(/\"/g, ""),
Session_id: arr[3].replace(/\"/g, ""),
Mem: arr[4].replace(/\"/g, ""),
Status: arr[5].replace(/\"/g, ""),
User: arr[6].replace(/\"/g, ""),
CPU: arr[7].replace(/\"/g, ""),
Title: arr[8].replace(/\"/g, "")
}
if (!name || t.Name.toLowerCase() == name.toLowerCase()) {
ret.push(t)
// WScript.Echo(tasks[i])
// WScript.Echo(t)
}
}
return ret
}
path_arr = function () {
// var pathCur = exec_("cmd /c @echo %PATH%", false);
pathCur = objEnv("PATH")
WScript.Echo(pathCur);
var arr = pathCur.split(';');
return arr;
}
path_add = function (pth) {
oldSystemPath = objEnv("PATH")
newSystemPath = pth + ";" + oldSystemPath
arr = path_arr()
var bAdd = true;
for (var i in arr) {
if (pth.toLowerCase() == arr[i].toLowerCase()) {
bAdd = false;
};
WScript.Echo(i + " (" + bAdd + "):" + arr[i]);
}
if (bAdd) {
var cmd = "cmd /c pathed add \"" + pth + "\"";
WScript.Echo("+++ adding (" + cmd + ")");
var ret3 = run(cmd);
WScript.Echo(ret3);
} else {
WScript.Echo("--- skip (" + pth + ") already exists");
}
}
assoc = function (exts, ftype, apps, switches, name_, pathtoicon_) {
if (!switches) switches = "\"%1\" %*";
for (e in exts) {
ext = exts[e]
for (a in apps) {
app = apps[a].replace(/\//g, "/");
if (!name_) name = get_fn(app).n;
else name = name_;
if (!pathtoicon_) pathtoicon = app + ",0";
else pathtoicon = pathtoicon_;
WScript.Echo("\n========== ext: " + ext + "\t | ftype: " + ftype + " | app: " + app + " | switches: " + switches + " | name: " + name + " | icon: " + pathtoicon);
cmd = "cmd /c @reg add \"HKCU/Software/Microsoft/Windows/CurrentVersion/Explorer/FileExts/." + ext + "/OpenWithProgids\" /v \"" + name + "\" /d \"" + name + "\" /f >NUL";
WScript.Echo(cmd + " - " + sh.Exec(cmd));
cmd = "cmd /c @reg add \"HKCU/Software/Microsoft/Windows/CurrentVersion/Explorer/FileExts/." + ext + "/UserChoice\" /v \"ProgId\" /d \"" + name + "\" /f >NUL";
WScript.Echo(cmd + " - " + sh.Exec(cmd));
cmd = "cmd /c @reg add \"HKCU/Software/Microsoft/Windows/CurrentVersion/Explorer/FileExts/." + ext + "/OpenWithList\" /v \"" + name + "\" /d \"" + name + "\" /f >NUL";
WScript.Echo(cmd + " - " + sh.Exec(cmd));
cmd = "cmd /c @reg add \"HKCR/" + name + "\" /ve /d \"" + name + "\" /f >NUL";
WScript.Echo(cmd + " - " + sh.Exec(cmd));
cmd = "cmd /c @reg add \"HKCR/" + name + "/DefaultIcon\" /ve /d \"" + pathtoicon + "\" /f >NUL";
WScript.Echo(cmd + " - " + sh.Exec(cmd));
// cmd = "cmd /c @reg add \"HKCU/" + name + "/DefaultIcon\" /ve /d \"" + pathtoicon + "\" /f";
// WScript.Echo(cmd + " - " + sh.Exec(cmd));
// /\Registry\HKCR\FirefoxHTML-7F96AA79EBB22004\shell\open\command\(Default)
// /\Registry\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.shp\UserChoice\ProgId
// REG ADD HKCR\%extension%\ /t REG_SZ /d %ftypename% /f
cmd = "cmd /c @reg add \"HKCR/" + name + "\" /t REG_SZ /d \"" + app + "\" " + switches + " /f >NUL";
WScript.Echo(cmd + " - " + sh.Exec(cmd));
cmd = "cmd /c @reg add \"HKCR/Applications/" + name + ".exe/shell/open/command\" /t REG_SZ /v \"(Default)\" /d \"\"" + app + "\" " + switches + "\" /f >NUL";
WScript.Echo(cmd + " - " + sh.Exec(cmd));
cmd = "cmd /c @reg add \"HKCR/Applications/" + name + ".exe/shell/edit/command\" /t REG_SZ /v \"@\" /d \"\"" + app + "\" " + switches + "\" /f >NUL";
WScript.Echo(cmd + " - " + sh.Exec(cmd));
cmd = "cmd /c @reg add \"HKCR/Applications/" + name + ".exe/SupportedTypes\" /t REG_SZ /v \"." + ext + "\" /d \"\" /f >NUL";
WScript.Echo(cmd + " - " + sh.Exec(cmd));
cmd = "cmd /c @reg add \"HKCR/." + ext + "/OpenWithProgids\" /t REG_SZ /v \"" + name + "\" /d \"\" /f >NUL";
WScript.Echo(cmd + " - " + sh.Exec(cmd));
cmd = "cmd /c @reg add \"HKLM/SOFTWARE/Classes/" + name + "/DefaultIcon\" /t REG_SZ /d \"" + pathtoicon + "\" /f >NUL"
WScript.Echo(cmd + " - " + sh.Exec(cmd));
//! ----------------- assoc .txt=txtfile
ftype = name
cmd = "cmd /c assoc ." + ext + "=" + ftype
WScript.Echo(cmd + " - " + sh.Exec(cmd));
//! ----------------- ftype txtfile="G:\Program Files\Windows NT\Accessories\wordpad.exe" "%1"
cmd = "cmd /c ftype " + ftype + "=\"" + app + "\" " + switches;
WScript.Echo(cmd + " - " + sh.Exec(cmd));
}
}
}
path = function (pth) {
if (!pth) return objEnv("PATH")
set("PATH", pth)
}
// function getMethods(obj) {
// var result = [];
// for (var id in obj) {
// try {
// if (typeof(obj[id]) == "function") {
// result.push(id + ": " + obj[id].toString());
// }
// } catch (err) {
// result.push(id + ": inaccessible");
// }
// }
// return result;
// }
// function getVal(obj) {
// console.log(Object.keys(obj));
// var result = [];
// for (var id in obj) {
// console.log("arg " + id)
// console.log("o " + obj[id])
// console.log(typeof(obj[id]))
// try {
// if (typeof(obj[id]) == "function") {
// // result.push(id + ": " + obj[id].toString());
// }
// } catch (err) {
// result.push(id + ": inaccessible");
// }
// }
// return result;
// }
// function objectToString(obj) {
// var str = '';
// var i = 0;
// for (var key in obj) {
// if (obj.hasOwnProperty(key)) {
// if (typeof obj[key] == 'object') {
// if (obj[key] instanceof Array) {
// str += key + ' : [ ';
// for (var j = 0; j < obj[key].length; j++) {
// if (typeof obj[key][j] == 'object') {
// str += '{' + objectToString(obj[key][j]) + (j > 0 ? ',' : '') + '}';
// } else {
// str += '\'' + obj[key][j] + '\'' + (j > 0 ? ',' : ''); //non objects would be represented as strings
// }
// }
// str += ']' + (i > 0 ? ',' : '')
// } else {
// str += key + ' : { ' + objectToString(obj[key]) + '} ' + (i > 0 ? ',' : '');
// }
// } else {
// str += key + ':\'' + obj[key] + '\'' + (i > 0 ? ',' : '');
// }
// i++;
// }
// }
// return str;
// }
// function obj2str(obj) {
// var tabjson = [];
// for (var p in obj) {
// if (obj.hasOwnProperty(p)) {
// tabjson.push('"' + p + '"' + ':' + obj[p]);
// }
// }
// tabjson.push()
// return '{' + tabjson.join(',') + '}';
// }
office2pdf = function (source, target) {
fn = get_fn(source)
if (!target) target = fn.pn + ".pdf";
switch (fn.x) {
case "docx":
case "doc":
WScript.Echo("Converting Word: " + source + " to " + target)
app = new ActiveXObject("Word.Application");
break;
case "xlsx":
case "xls":
WScript.Echo("Converting Excel: " + source + " to " + target)
app = new ActiveXObject("Excel.Application");
break;
case "pptx":
case "ppt":
WScript.Echo("Converting PowerPoint: " + source + " to " + target)
app = new ActiveXObject("PowerPoint.Application");
break;
default:
alert("wrong file format");
}
doc = app.Documents.Open(source, 0, 0, 0)
app.Visible = false
app.ActiveDocument.SaveAs(target, 17)
// doc.SaveCopyAs(target, 32);
// doc.SaveAs(target, 32);
doc.Close();
app.Quit();
return 0;
}
getNetworkAdapterList = function () {
var colItems = objWMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter", null, 48);
var objItem = new Enumerator(colItems);
for (; !objItem.atEnd(); objItem.moveNext()) {
WScript.Echo("Win32_NetworkAdapter instance: " + objItem.item().Name);
}
}
getWindowsVer = function () {
var enumItems = new Enumerator(objWMIService.ExecQuery("Select * from Win32_OperatingSystem", null, 48));
var item, p, s;
for (; !enumItems.atEnd(); enumItems.moveNext()) {
item = enumItems.item();
s = item.Caption.toLowerCase();
p = s.indexOf("windows ");
if (!(p < 0)) {
s = s.substr(p + 8);
p = s.indexOf(" ");
s = (p < 0) ? s : s.substr(0, p);
}
}
return s
}
del = function (fn) {
console.log('Deleting ' + fn);
if (fs.FileExists(fn))
fs.DeleteFile(fn);
}
download = function (sSourceUrl, sDestFile) {
objXMLHTTP.onreadystatechange = function () {
if (objXMLHTTP.readyState === 4) {
objADOStream.open();
objADOStream.type = 1; //! Binary
objADOStream.write(objXMLHTTP.ResponseBody);
objADOStream.position = 0;
if (fs.FileExists(sDestFile))
fs.DeleteFile(sDestFile);
objADOStream.saveToFile(sDestFile, 2);
objADOStream.close();
}
};
objXMLHTTP.open("GET", sSourceUrl, false);
objXMLHTTP.send();
}
getProcess = function (proc) {
ret = 0
show = true
var enumItems = new Enumerator(wmi.ExecQuery("Select * from Win32_Process", null, 48));
for (; !enumItems.atEnd(); enumItems.moveNext()) {
item = enumItems.item();
if (show) {
WScript.Echo("\nName : " + item.Name)
WScript.Echo(" CreationClassName : " + item.CreationClassName)
WScript.Echo(" Caption : " + item.Caption)
WScript.Echo(" CommandLine : " + item.CommandLine)
WScript.Echo(" CreationDate : " + item.CreationDate)
WScript.Echo(" CSCreationClassName : " + item.CSCreationClassName)
WScript.Echo(" CSName : " + item.CSName)
WScript.Echo(" Description : " + item.Description)
WScript.Echo(" ExecutablePath : " + item.ExecutablePath)
WScript.Echo(" ExecutionState : " + item.ExecutionState)
WScript.Echo(" Handle : " + item.Handle)
WScript.Echo(" HandleCount : " + item.HandleCount)
WScript.Echo(" InstallDate : " + item.InstallDate)
WScript.Echo(" KernelModeTime : " + item.KernelModeTime)
WScript.Echo(" MaximumWorkingSetSize : " + item.MaximumWorkingSetSize)
WScript.Echo(" MinimumWorkingSetSize : " + item.MinimumWorkingSetSize)
WScript.Echo(" Name : " + item.Name)
WScript.Echo(" OSCreationClassName : " + item.OSCreationClassName)
WScript.Echo(" OSName : " + item.OSName)
WScript.Echo(" OtherOperationCount : " + item.OtherOperationCount)
WScript.Echo(" OtherTransferCount : " + item.OtherTransferCount)
WScript.Echo(" PageFaults : " + item.PageFaults)
WScript.Echo(" PageFileUsage : " + item.PageFileUsage)
WScript.Echo(" ParentProcessId : " + item.ParentProcessId)
WScript.Echo(" PeakPageFileUsage : " + item.PeakPageFileUsage)
WScript.Echo(" PeakVirtualSize : " + item.PeakVirtualSize)
WScript.Echo(" PeakWorkingSetSize : " + item.PeakWorkingSetSize)
WScript.Echo(" Priority : " + item.Priority)
WScript.Echo(" PrivatePageCount : " + item.PrivatePageCount)
WScript.Echo(" ProcessId : " + item.ProcessId)
WScript.Echo(" QuotaNonPagedPoolUsage : " + item.QuotaNonPagedPoolUsage)
WScript.Echo(" QuotaPagedPoolUsage : " + item.QuotaPagedPoolUsage)
WScript.Echo(" QuotaPeakNonPagedPoolUsage : " + item.QuotaPeakNonPagedPoolUsage)
WScript.Echo(" QuotaPeakPagedPoolUsage : " + item.QuotaPeakPagedPoolUsage)
WScript.Echo(" ReadOperationCount : " + item.ReadOperationCount)
WScript.Echo(" ReadTransferCount : " + item.ReadTransferCount)
WScript.Echo(" SessionId : " + item.SessionId)
WScript.Echo(" Status : " + item.Status)
WScript.Echo(" TerminationDate : " + item.TerminationDate)
WScript.Echo(" ThreadCount : " + item.ThreadCount)
WScript.Echo(" UserModeTime : " + item.UserModeTime)
WScript.Echo(" VirtualSize : " + item.VirtualSize)
WScript.Echo(" WindowsVersion : " + item.WindowsVersion)
WScript.Echo(" WorkingSetSize : " + item.WorkingSetSize)
WScript.Echo(" WriteOperationCount : " + item.WriteOperationCount)
WScript.Echo(" WriteTransferCount : " + item.WriteTransferCount)
}
//! item.Terminate //process terminated
if (isNaN(proc)) {
if (proc == item.Name)
ret = item
} else {
if (proc == item.ProcessID)
ret = item
}
}
wsh.Run("%comspec% " + "/K " + gid, 0)
return ret;
}
CHOICE = function (str, characters) {
if (!characters) characters = 2;
WScript.StdOut.Write("\r" + str);
ret = WScript.StdIn.ReadLine(characters);
WScript.Echo("You entered " + ret);
}
logOff = lock = function (delay) {
var OpSysSet = GetObject("winmgmts:{authenticationlevel=Pkt," + "(Shutdown)}").ExecQuery("select * from Win32_OperatingSystem where " + "Primary=true")
WScript.Sleep(delay * 1000)
for (OpSys in OpSysSet) {
retVal = OpSys.Win32Shutdown(6)
}
}
reboot = function (delay) {
var OpSysSet = GetObject("winmgmts:{authenticationlevel=Pkt," + "(Shutdown)}").ExecQuery("select * from Win32_OperatingSystem where " + "Primary=true")
WScript.Sleep(delay * 1000)
for (OpSys in OpSysSet) {
retVal = OpSys.Win32Shutdown(6)
}
}
shutdown = poweroff = function (delay) {
var OpSysSet = GetObject("winmgmts:{authenticationlevel=Pkt," + "(Shutdown)}").ExecQuery("select * from Win32_OperatingSystem where " + "Primary=true")
WScript.Sleep(delay * 1000)
for (OpSys in OpSysSet) {
retVal = OpSys.Win32Shutdown(6)
}
}
popup = function () {
timeout = 30
while (timeout > 0) {
timeout = timeout - 1
intReturn = objShell.Popup("Hibernation about to initiate. Abort?" + " " + "Time until hibernation : " + timeout, 1, "Hibernation", 4096)
if (intReturn == 0) {
Wscript.Quit
}
}
}
pause = function () {
WScript.Echo("Press the ENTER key to continue...");
while (!WScript.StdIn.AtEndOfLine)
WScript.StdIn.Read(1);
}
//!---------------------------------- Ali ---------------------------
//!---------------------------------- Ali Defaults ---------------------------
var sh = wsh = wshShell = WshShell = shell = oShell = objShell = WScript.CreateObject("WSCript.shell");
var wshNet = objNet = wshNetwork = objNetwork = WScript.CreateObject("WScript.Network")
try {
var IEDbx = oHTML = WScript.CreateObject("InternetExplorer.Application")
oHTML.Navigate("about:blank")
str = oHTML.Document.ParentWindow.ClipboardData.GetData("Text")
echo(str)
} catch (e) {
}
try {
oHTM = WScript.CreateObject("HTMLFile")
getClipboard = function () {
return oHTM.parentWindow.clipboardData.getData("Text")
}
getClipboard_img = function () {
return oHTM.parentWindow.clipboardData.getData("image/png")
}
} catch (e) {
}
try {
var oPrcEnv = env = objEnv = oProcEnv = sh.Environment("Process")
var oSysEnv = oSystemEnv = sh.Environment("SYSTEM");
var oVolEnv = oVolatileEnv = sh.Environment("Volatile");
var oUsrEnv = oUserEnv = sh.Environment("User");
} catch (e) {
echo("Error 104: " + e);
}
//!-----------------------------------
vbOK = wshOkDialog = 0; //! 0x0 Show�OK
vbCancel = btnOK_Cancel = 1; //! 0x1 Show�OK�and�Cancel
vbAbort = btnAbort_Retry_Ignore = 2; //! 0x2 Show�Abort,�Retry, and�Ignore
vbRetry = btnYes_No_Cancel = 3; //! 0x3 Show�Yes,�No, and�Cancel
btnYes_No = 4; //! 0x4 Show�Yes�and�No
btnRetry_Cancel = 5; //! 0x5 Show�Retry�and�Cancel
btnCancel_TryAgain_Continue = 6; //! 0x6 Show�Cancel,�Try Again, and�Continue
vbCritical = icon_Stop = 16; //! 0x10 Show "Stop Mark"
vbQuestion = icon_Question = 32; //! 0x20 Show "Question Mark"
vbExclamation = icon_Exclamation = 48; //! 0x30 Show "Exclamation Mark"
vbInformation = icon_Information = 64; //! 0x40 Show "Information Mark"
vbDefaultButton2 = 256; //! 0x100 The second button is the default button.
vbDefaultButton3 = 512; //! 0x200 The third button is the default button.
opt_topmost = 4096; //! 0x1000 The message box is a system modal message box and appears in a topmost window.
opt_right_text = 524288; //! 0x80000 The text is right-justified.
opt_RTE = 1048576; //! 0x100000 The message and caption text display in right-to-left reading order, which is useful for some languages.
ret_timeout = ret_elapsed = -1; //! The user did not click a button before nSecondsToWait seconds elapsed.
ret_Ok = 1;
ret_Cancel = 2;
ret_Abort = 3;
ret_Retry = 4;
ret_Ignore = 5;
ret_Yes = 6;
ret_No = 7;
ret_try_again = 10;
ret_Continue = 11;
var vbArr = "OK,Cancel,Abort,Retry,Ignore,Yes,No,OKOnly,OKCancel,AbortRetryIgnore,YesNoCancel,YesNo,RetryCancel,Critical,Question,Exclamation,Information,DefaultButton1,DefaultButton2,DefaultButton3".split(",");
for (var i = 0; i < vbArr.length; i++) {
//! this["vb" + vbArr[i]] = eval("vb" + vbArr[i]);
}
//!-----------------------------------
computerName = ".";
var wmi = oWMI = WmiService = objWMIService = GetObject("winmgmts://" + computerName + "/root/cimv2");
var oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!//" + computerName + "/root/default:StdRegProv")
var objProcess = GetObject("winmgmts:root/cimv2:Win32_Process")
var objXMLHTTP = new ActiveXObject("MSXML2.XMLHTTP");
var objADOStream = Stream = new ActiveXObject("ADODB.Stream");
var TypeLib = new ActiveXObject("Scriptlet.TypeLib")
var gid = TypeLib.Guid.substring(0, 38);
console = {
log: function (s) {
if (s instanceof Object)
printObj(s, "");
else
WScript.echo(s);
},
print: function (s) {
console.log(s)
}
}
fs_ = {
rmdirSync: function (foldername) {
if (foldername) {
try {
WScript.Echo("deleting: " + foldername);
fs.DeleteFolder(foldername)
} catch (e) {
WScript.echo("ERROR! Cannot remove " + e.number + ", " + e.description + ", foldername=" + foldername);
// WScript.quit();
return;
}
}
},
rmdir: function (foldername) {
if (foldername) {
try {
WScript.Echo("deleting: " + foldername);
fs.DeleteFolder(foldername)
} catch (e) {
WScript.echo("ERROR! Cannot remove " + e.number + ", " + e.description + ", foldername=" + foldername);
// WScript.quit();
return;
}
}
}
}
var argc = WScript.Arguments.length;
var argv = [];
for (var i = 0; i < argc; i++)
argv.push(WScript.Arguments(i)); // copy args to argv
if (is64()) {
// example: var name = InputBox('Hi.\nWhat is your name?', "Title");
//! call 32b ver of cscript, since ScriptControl?, which is being used to allow JScript to call VBScript functions, isn?t available in the 64bit version of cscript or WScript.
(function (vbe) {
vbe.Language = "VBScript";
vbe.AllowUI = true;
var constants = "OK,Cancel,Abort,Retry,Ignore,Yes,No,OKOnly,OKCancel,AbortRetryIgnore,YesNoCancel,YesNo,RetryCancel,Critical,Question,Exclamation,Information,DefaultButton1,DefaultButton2,DefaultButton3".split(",");
for (var i = 0; constants[i]; i++) {
this["vb" + constants[i]] = vbe.eval("vb" + constants[i]);
}
InputBox = function (prompt, title, msg, xpos, ypos) {
return vbe.eval('InputBox(' + [
toVBStringParam(prompt),
toVBStringParam(title),
toVBStringParam(msg),
xpos != null ? xpos : "Empty",
ypos != null ? ypos : "Empty"
].join(",") + ')');
};
MsgBox = function (prompt, buttons, title) {
return vbe.eval('MsgBox(' + [
toVBStringParam(prompt),
buttons != null ? buttons : "Empty",
toVBStringParam(title)
].join(",") + ')');
};
function toVBStringParam(str) {
return str != null ? 'Unescape("' + escape(str + "") + '")' : "Empty";
}
})(new ActiveXObject("ScriptControl"));
}
//! Get ProcessID
get_pid = function (process_name) {
var handle = sh.Exec("tasklist.exe");
while (!handle.StdOut.AtEndOfStream) {
var p = handle.StdOut.ReadLine();
p = p.replace(/ /g, " ").replace(/ /g, " ").replace(/ /g, " ").replace(/ /g, " ").replace(/ /g, " ");
p = p.split(' ');
//console.log(p[0])
if (p[0] == process_name) {
var pid = p[1];
console.log(pid);
}
// WScript.Echo("Failed to find application with title: " + title);
}
// clean up
handle = null;
}
//!---------------------------------- Ali2 ---------------------------
// lib2 = eval(fs.OpenTextFile(new ActiveXObject('WScript.Shell').ExpandEnvironmentStrings("%ALIBROOT%alib.js"), 1).ReadAll()); //! Shared lib between NodeJS and JScript