Skip to content

Instantly share code, notes, and snippets.

@fliedonion
Last active June 10, 2023 14:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fliedonion/571da78b27fdc2cae098 to your computer and use it in GitHub Desktop.
Save fliedonion/571da78b27fdc2cae098 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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.

@x5engine
Copy link

yo yoyoy

Copy link

ghost commented May 10, 2021

Thanks!, i'll try it

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