Instantly share code, notes, and snippets.

Embed
What would you like to do?
How to Embed Javascript code in Windows Bat File.
Summary One example for embed javascript into windows bat file without any external tools or files.
Env windows node.js jscript
if ("0"=="1") /* "Elevate privileges if need. And run node.js script. "
setlocal ENABLEDELAYEDEXPANSION
@echo off
@NET FILE 1>NUL 2>NUL
if not '%errorlevel%' == '0' (
@rem if access denied error, run self as wsh-jscript to elevate.
goto :UAC_ELEVATE
) else (
@rem otherwise run.
goto :NODE_JS
)
goto :EOF
:UAC_ELEVATE
@rem Pass this file's filename as command line arguments.
@cscript //nologo //e:jscript "%~f0" "%~f0"
exit /b
:NODE_JS
node "%~f0"
pause
exit /b
*/ {}
// javascript block.
function wscriptMain(filename){
// Run this bat file again with "runas" parameter
var uac = new ActiveXObject("Shell.Application");
uac.ShellExecute(filename, "", "", "runas", 1);
}
function nodeMain(){
console.log("Hello, Node js");
console.log(process.version);
}
// determine WSH or node.
if(typeof console === 'undefined'){
wscriptMain(WScript.Arguments(0));
}else{
nodeMain();
}
if ("0"=="1") /* "Unfortunately, this line do nothing but echo back to your console. "
@echo bat file start.
setlocal ENABLEDELAYEDEXPANSION
@echo off
REM You can embed node.js ( And / Or ) WSH Jscript to single bat file.
call :JSCRIPT
call :NODE_JS
goto :EOF
:JSCRIPT
@REM execute self as WSH JScript
@cscript //nologo //e:jscript "%~f0"
exit /b
:NODE_JS
@REM You can also edit path variable here to set or change node interpreter.
node "%~f0"
pause
exit /b
*/ {}
// Do not remove {} above. ( Removing this line is ok. )
// javascript block.
function wscriptMain(){
WScript.Echo("Hello, JScript");
var fso = new ActiveXObject("Scripting.FileSystemObject");
WScript.Echo(fso.FolderExists("C:\\windows").toString());
fso = null;
}
function nodeMain(){
console.log("Hello, Node js");
console.log(process.version);
}
// determine WSH or node.
if(typeof console === 'undefined'){
wscriptMain();
}else{
nodeMain();
}
@fliedonion

This comment has been minimized.

Owner

fliedonion commented Aug 7, 2015

Here is two sample files.
Only run script, see js_embeded_bat.bat as a sample.
If you want to elevate privileges, see js_embedded_within_bat_uac.bat.

@meteorplus

This comment has been minimized.

meteorplus commented Oct 27, 2018

yo yoyoy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment