Wrapping Applications with a .bat Script - command-line

I recently decided to start using Google's command-line JavaScript compiler (Closure Compiler) to minify JavaScript in my web application. Unfortunately, the compiler is written in Java so the command I have to type to use the compiler is somewhat cumbersome:
java -jar compiler.jar --js hello.js --js_output_file hello-compiled.js
What would be the simplest way for me to wrap this in .bat file that would allow me to simply type closure hello.js hello-compiled.js, while still allowing me to use closure's other command line flags such as --warning-level and --help?

:Start
#echo off
if "%1"=="" Echo Error - input and output parameters were not specified.&goto End
if "%2"=="" Echo Error - output parameter was not specified.&goto End
if not exist %1 Echo Error - input file does not exist.&goto End
set infile=%1
set outfile=%2
set "params="
:Loop
if "%3"=="" goto Continue
set params=%params% %3
shift
goto Loop
:Continue
java -jar compiler.jar --js %infile% --js_output_file %outfile% %params%
set "infile="
set "outfile="
set "params="
:End

I don't know how automated you want this to be, but this will prompt you for your script, your compiled output file, and if you want any extra parameters.
Easily editable if you want more options.
#echo off
set /p script=Script file:
set /p compiled=Compiled script:
set /p params=Enter any extra params (leave blank if none):
if defined params (
java -jar compiler.jar --js %script% --js_output_file %compiled% %params%
) else (
java -jar compiler.jar --js %script% --js_output_file %compiled%
)
echo Done
pause >nul

Related

Why is my GOTO statement not working (batch)

It always goes to the first lapel no matter what is the input
I saw other posts with the same issue but none of the syntax mistakes they made were present in my script.
Here is the script :
#echo off
cls
cd /d %~dp0
echo "Include files? [Y/N]"
set /p option=
if %option%=="Y" GOTO yes
if %option%=="y" GOTO yes
if %option%=="N" GOTO no
if %option%=="n" GOTO no
:yes
cls
powershell -command "iex \"tree /f\" > \"tree-filed.txt\""
GOTO end
:no
cls
powershell -command "iex \"tree\" > \"tree-folders.txt\""
GOTO end
:end
cls
echo the tree list was created.
pause
What am I missing?
rifteyy's solution is effective, but some background information may be helpful:
As Squashman notes, an if conditional either requires both sides to be either (double-)quoted or unquoted; that is, both if %option%==y ... and if "%option%"=="y" ... work:
The double-quoted form is more robust, as it also handles values with metacharacters such as & correctly, but the match must be exact with respect to presence or absence of spaces.
Conversely, only the unquoted form is forgiving of leading and trailing spaces; e.g. if %option%==y ... still works if the user entered y rather than just y.
You can use if's /I option to make the comparison case-insensitive, which obviates the need to check for y and Y separately, for instance. help if shows more information.
tree.com is a stand-alone executable that can be called from any (Windows) shell, so there is generally no good reason to call PowerShell (powershell.exe, which is expensive), given that you can invoke tree directly from your batch file - though you may need PowerShell to control the character encoding of the output files.[1]
As an aside: Inside PowerShell there is no need for Invoke-Expression (iex), which should generally be avoided; the best way to invoke an external executable such as tree.com fundamentally works the same as from cmd.exe (see below).
If you do need PowerShell, call it as follows, for instance:
powershell -command "tree > tree-folders.txt"
Therefore, a streamlined version of your batch file would look like this (cls commands omitted):
#echo off
cd /d "%~dp0"
:prompt
echo "Include files? [Y/N/Q]"
set /p option=
if /I "%option%"=="y" GOTO yes
if /I "%option%"=="n" GOTO no
if /I "%option%"=="q" GOTO :eof
goto prompt
:yes
tree /f > tree-files.txt
GOTO end
:no
tree > tree-folders.txt
GOTO end
:end
echo the tree list was created.
pause
As Stephan points out, the standard choice.exe utility offers a simpler prompting solution:
choice /c ynq /m "Include files?"
if %ERRORLEVEL% EQU 1 goto yes
if %ERRORLEVEL% EQU 2 goto no
goto :eof
choice.exe:
is case-insensitive by default (use /CS for case-sensitivity)
accepts only a single input character from the user, which instantly exits the prompt (no Enter keypress required), with the %ERRORLEVEL% variable set to the 1-based position of the character in the list of permitted characters passed to /C
Note: The above deliberately uses, e.g., if %ERRORLEVEL% EQU 1 rather than if ERRORLEVEL 1, because the latter uses equal-or-greater logic, which would require you to reverse the order of the branching statements.
automatically validates the input (beeps if an invalid character is typed)
See choice /? for more information.
[1] However, you do need PowerShell if the command's output contains non-ASCII characters and you want the output redirection (>) to create UTF-16LE ("Unicode") files (Windows PowerShell) or (BOM-less) UTF-8 files (PowerShell (Core) v6+). Using > from cmd.exe results in OEM-encoded files, based on the console's code page, reported via chcp. Alternatively, you could switch the console code page to (BOM-less) UTF-8, via chcp 65001, but that wouldn't work with tree.com, because it is too old to support this code page. By contrast, it would work with the output from dir, for instance.
You must use brackets in IF statement also, if you did not, it will automatically do the actions under the IF statements.
#echo off
cls
cd /d %~dp0
echo "Include files? [Y/N]"
set /p option=
if "%option%"=="Y" GOTO yes
if "%option%"=="y" GOTO yes
if "%option%"=="N" GOTO no
if "%option%"=="n" GOTO no
:yes
cls
powershell -command "iex \"tree /f\" > \"tree-filed.txt\""
GOTO end
:no
cls
powershell -command "iex \"tree\" > \"tree-folders.txt\""
GOTO end
:end
cls
echo the tree list was created.
pause

Is there a tag I could add to a ".bat" file to stop command window being displayed [duplicate]

How can I run a CMD or .bat file in silent mode? I'm looking to prevent the CMD interface from being shown to the user.
Include the phrase:
#echo off
right at the top of your bat script.
I have proposed in StackOverflow question a way to run a batch file in the background (no DOS windows displayed)
That should answer your question.
Here it is:
From your first script, call your second script with the following line:
wscript.exe invis.vbs run.bat %*
Actually, you are calling a vbs script with:
the [path]\name of your script
all the other arguments needed by your script (%*)
Then, invis.vbs will call your script with the Windows Script Host Run() method, which takes:
intWindowStyle : 0 means "invisible windows"
bWaitOnReturn : false means your first script does not need to wait for your second script to finish
See the question for the full invis.vbs script:
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False
^
means "invisible window" ---|
Update after Tammen's feedback:
If you are in a DOS session and you want to launch another script "in the background", a simple /b (as detailed in the same aforementioned question) can be enough:
You can use start /b second.bat to launch a second batch file asynchronously from your first that shares your first one's window.
I think this is the easiest and shortest solution to running a batch file without opening the DOS window, it can be very distracting when you want to schedule a set of commands to run periodically, so the DOS window keeps popping up, here is your solution.
Use a VBS Script to call the batch file ...
Set WshShell = CreateObject("WScript.Shell" )
WshShell.Run chr(34) & "C:\Batch Files\ mycommands.bat" & Chr(34), 0
Set WshShell = Nothing
Copy the lines above to an editor and save the file with .VBS extension. Edit the .BAT file name and path accordingly.
Use Advanced BAT to EXE Converter from http://www.battoexeconverter.com
This will allow you to embed any additional binaries with your batch file in to one stand alone completely silent EXE and its freeware
Use Bat To Exe Converter to do this
http://download.cnet.com/Bat-To-Exe-Converter/3000-2069_4-10555897.html (Choose Direct Download Link)
1 - Open Bat to Exe Converter, select your Bat file.
2 - In Option menu select "Invisible Application", then press compile button.
Done!
Try SilentCMD. This is a small freeware program that executes a batch file without displaying the command prompt window.
If i want to run command promt in silent mode, then there is a simple vbs command:
Set ws=CreateObject("WScript.Shell")
ws.Run "TASKKILL.exe /F /IM iexplore.exe"
if i wanted to open an url in cmd silently, then here is a code:
Set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("iexplore.exe http://otaxi.ge/log/index.php", 0)
'wait 10 seconds
WScript.sleep 10000
Set ws=CreateObject("WScript.Shell")
ws.Run "TASKKILL.exe /F /IM iexplore.exe"
I'm pretty confident I like this method the best. Copy and paste the code below into a .vbs file. From there you'll call the batch file... so make sure you edit the last line to specify the path and name of the batch file (which should contain the file you'd like to launch or perform the actions you need performed)
Const HIDDEN_WINDOW = 12
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = HIDDEN_WINDOW
Set objProcess = GetObject("winmgmts:root\cimv2:Win32_Process")
errReturn = objProcess.Create("C:\PathOfFile\name.bat", null, objConfig, intProcessID)
It definitely worked for me. Comments are welcomed :)
Another way of doing it, without 3rd party programs nor converters ("batch to exe" programs actually just put your batch file in the tmp folder and then run it silently so anyone can just fetch it from there an get your code) no vbs files (because nobody knows vbs) just one line at the beginning of the batch file.
#echo off > NUL
The below silent .bat file code prevents the need to have two bat files (using "goto" and ":").
It does it all in the same .bat file. Tested and confirmed working in Windows 10
Make sure you replace "C:\pathToFile\ThisBatFile.bat " with the path to this same .bat file! Keep the space after ".bat".
#echo off
if [%1]==[] (
goto PreSilentCall
) else (
goto SilentCall
)
:PreSilentCall
REM Insert code here you want to have happen BEFORE this same .bat file is called silently
REM such as setting paths like the below two lines
set WorkingDirWithSlash=%~dp0
set WorkingDirectory=%WorkingDirWithSlash:~0,-1%
REM below code will run this same file silently, but will go to the SilentCall section
cd C:\Windows\System32
if exist C:\Windows\Temp\invis.vbs ( del C:\Windows\Temp\invis.vbs /f /q )
echo CreateObject("Wscript.Shell").Run "C:\pathToFile\ThisBatFile.bat " ^& WScript.Arguments(0), 0, False > C:\Windows\Temp\invis.vbs
wscript.exe C:\Windows\Temp\invis.vbs Initialized
if %ERRORLEVEL%==0 (
echo Successfully started SilentCall code. This command prompt can now be exited.
goto Exit
)
:SilentCall
cd %WorkingDirectory%
REM Insert code you want to be done silently.
REM Make sure this section has no errors as you won't be able to tell if there are any,
REM since it will be running silently. You can add a greater than symbol at the end of
REM your commands in this section to output the results to a .txt file for the purpose
REM of debugging this section of code.
:Exit
If your .bat file needs more than just the "Initialized" argument (which tells the bat file to go to :SilentCall section), add "^& WScript.Arguments(1)," , "^& WScript.Arguments(2)," ,etc. depending on the number of arguments, then edit the line where wscript.exe is called:
"wscript.exe C:\Windows\Temp\invis.vbs Initialized BatFileArgOne BatFileArgTwo"
I'm created RunApp to do such a job and also using it in my production env, hope it's helps.
The config like below:
file: config.arg
:style:hidden
MyBatchFile.bat
arg1
arg2
And launch runapp.exe instead.

How to launch html report from cake (build)

I'm using cake in my projects to build, run unit tests, check code coverage and then generate an HTML report (using ReportGenerator). This is all working correctly, and I can open the generated report in my browser.
However, when I was previously using a dos batch file to do this, it would also launch my default browser and load the report after it was generated, but I can't find a way to do that with cake.
Here are the contents of the batch file I've been using:
#ECHO OFF
SET SearchDirectory=%~dp0Grapevine.Tests\bin\Debug
SET DllContainingTests=%~dp0Grapevine.Tests\bin\Debug\Grapevine.Tests.dll
for /R "%~dp0packages" %%a in (*) do if /I "%%~nxa"=="xunit.console.exe" SET TestRunnerExe=%%~dpnxa
for /R "%~dp0packages" %%a in (*) do if /I "%%~nxa"=="OpenCover.Console.exe" SET OpenCoverExe=%%~dpnxa
for /R "%~dp0packages" %%a in (*) do if /I "%%~nxa"=="ReportGenerator.exe" SET ReportGeneratorExe=%%~dpnxa
if not exist "%~dp0GeneratedReports" mkdir "%~dp0GeneratedReports"
call :RunOpenCoverUnitTestMetrics
if %errorlevel% equ 0 (
call :RunReportGeneratorOutput
)
if %errorlevel% equ 0 (
call :RunLaunchReport
)
exit /b %errorlevel%
:RunOpenCoverUnitTestMetrics
"%OpenCoverExe%" ^
-target:"%TestRunnerExe%" ^
-targetargs:"\"%DllContainingTests%\"" ^
-filter:"+[*]* -[*.Tests*]* -[*]*.*Config -[xunit*]* -[*]Grapevine.Interfaces.*" ^
-mergebyhash ^
-skipautoprops ^
-register:user ^
-output:"%~dp0GeneratedReports\CoverageReport.xml"^
-searchdirs:"%SearchDirectory%"
exit /b %errorlevel%
:RunReportGeneratorOutput
"%ReportGeneratorExe%" ^
-reports:"%~dp0\GeneratedReports\CoverageReport.xml" ^
-targetdir:"%~dp0\GeneratedReports\ReportGeneratorOutput"
exit /b %errorlevel%
:RunLaunchReport
start "report" "%~dp0\GeneratedReports\ReportGeneratorOutput\index.htm"
exit /b %errorlevel%
I have tried using the following:
StartProcess(new FilePath("./GeneratedReports/ReportGeneratorOutput/index.htm"));
To which I receive the following error:
An error occured when executing task 'generate-report'.
Error: The specified executable is not a valid application for this OS platform.
I have verified that the path is correct and the file exists, and that copy/pasting the file path on the command line indeed opens the file in my default browser.
I couldn't figure out a way to do this with just Cake, so I resorted to calling CMD with StartProcess:
if (IsRunningOnWindows()) {
StartProcess("cmd", new ProcessSettings {
Arguments = $"/C start \"\" {testCoverageReportPath}index.htm"
});
}
This works great for my needs.
You can do this using the StartProcess alias example:
FilePath reportpath = File("./GeneratedReports/ReportGeneratorOutput/index.htm");
StartProcess(reportpath);
What finally worked for me was this:
if (IsRunningOnWindows())
{
StartProcess("explorer.exe", reportPath);
}
Obviously, this won't work on non-windows environments, but that's outside the scope of my needs. Everything else I tried produced an error either that the file could not be found or that the executable was invalid for the OS.

cmd batch file removing characters fails

I am trying to write a custom deploy.cmd for our azure web app deployment. I created a test.cmd script to test removing the first and last character of a file path:
"D:\Program Files (x86)\npm\3.10.3\npm.cmd"
The reason is because the powershell script gets upset if it is not quoted, but the cmd file needs it to not be quoted to run correctly. My test script is:
echo off
setlocal enabledelayedexpansion
SET DEPLOYMENT_SOURCE=D:\home\site\wwwroot
SET NPM_CMD="D:\Program Files (x86)\npm\3.10.3\npm.cmd"
echo %NPM_CMD%
set NPM_CMD=%NPM_CMD:~1, -1%
echo %NPM_CMD%
pushd "%DEPLOYMENT_SOURCE%"
call "%NPM_CMD%" cache clean
call "%NPM_CMD%" install
pushd "%DEPLOYMENT_SOURCE%"
This works and npm is called correctly. So I took the:
set NPM_CMD=%NPM_CMD:~1, -1%
line and put it into my main deploy.cmd file:
echo off
setlocal enabledelayedexpansion
:: Setup
:: -----
echo starting deploy.cmd
echo -------------------
echo %*
SET all=%*
SET NPM_GLOBAL=%1
SET NPM_INFO=%2
echo all: %all%
echo NPM_GLOBAL: %NPM_GLOBAL%
echo NPM_INFO: %NPM_INFO%
SET DEPLOYMENT_SOURCE=D:\home\site\wwwroot
if NPM_GLOBAL=="True" (
REM install specific version of NPM
echo installing specific version of NPM # %NPM_INFO%
npm install -g npm#%NPM_INFO%
%NPM_CMD%=npm
) else (
SET NPM_CMD=%NPM_INFO%
set NPM_CMD=%NPM_CMD:~1, -1%
echo %NPM_CMD%
echo NPM_CMD set to %NPM_CMD%
)
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
echo Handling node.js deployment.
echo %DEPLOYMENT_SOURCE%
ECHO %DEPLOYMENT_SOURCE%\package.json
echo Install npm packages
IF EXIST "%DEPLOYMENT_SOURCE%\package.json" (
pushd "%DEPLOYMENT_SOURCE%"
echo Cleaning NPM cache.
call "%NPM_CMD%" cache clean
call "%NPM_CMD%" install
IF !ERRORLEVEL! NEQ 0 goto error
popd
)
This will give the following output:
PS D:\home\site\wwwroot> .\deploy.cmd False "D:\Program Files (x86)\npm\3.10.3\npm.cmd"
D:\home\site\wwwroot>echo off
starting deploy.cmd
-------------------
False "D:\Program Files (x86)\npm\3.10.3\npm.cmd"
all: False "D:\Program Files (x86)\npm\3.10.3\npm.cmd"
NPM_GLOBAL: False
NPM_INFO: "D:\Program Files (x86)\npm\3.10.3\npm.cmd"
ECHO is off.
NPM_CMD set to
'"~1, -1"' is not recognized as an internal or external command,
operable program or batch file.
Handling node.js deployment.
D:\home\site\wwwroot
D:\home\site\wwwroot\package.json
Install npm packages
Cleaning NPM cache.
PS D:\home\site\wwwroot> '"~1, -1"' is not recognized as an internal or external command,
operable program or batch file.
The system cannot find the batch label specified - error
I do not understand why it doesn't know how to remove the first and last character and why it errors. I can't see anything else wrong with the file.
Do not look after stripping surrounding quotes. Instead, define variables without surrounding double quotes as follows:
SET "DEPLOYMENT_SOURCE=D:\home\site\wwwroot"
SET "NPM_CMD=D:\Program Files (x86)\npm\3.10.3\npm.cmd"
and then use them surrounded in double quotes if necessary as follows:
echo %NPM_CMD%
pushd "%DEPLOYMENT_SOURCE%"
call "%NPM_CMD%" cache clean
call "%NPM_CMD%" install
To apply above to your main deploy.cmd file, read in call /?
…
In addition, expansion of batch script argument references (%0, %1,
etc.) have been changed as follows:
%* in a batch script refers to all the arguments (e.g. %1 %2 %3 %4 %5 ...)
Substitution of batch parameters (%n) has been enhanced. You can
now use the following optional syntax:
%~1 - expands %1 removing any surrounding quotes (")
%~f1 - expands %1 to a fully qualified path name
%~d1 - expands %1 to a drive letter only
%~p1 - expands %1 to a path only
Press any key to continue . . .
and apply it when necessary:
echo starting deploy.cmd
echo -------------------
echo %*
SET all=%*
SET "NPM_GLOBAL=%1" 1st parameter is not in double quotes already
SET "NPM_INFO=%~2" 2nd parameter is stripped of surrounding double quotes
Moreover, you need to apply delayed expansion using !variable! instead of %variable% for instance as follows:
(
SET "NPM_CMD=%NPM_INFO%"
rem not necessary now set "NPM_CMD=!NPM_CMD:~1, -1!"
echo !NPM_CMD!
echo NPM_CMD set to !NPM_CMD!
)
To remove quotes around a referenced string, insert a tilde (~) before the parameter number.
%1 to %~1
Changing the start of your batch file to this;
echo starting deploy.cmd
echo -------------------
echo %*
SET all=%*
SET NPM_GLOBAL=%~1
SET NPM_INFO=%~2

Is it possible to convert the epsilon or UltraEdit macro to exe?

If anyone know about how to convert the epsilon and UltraEdit macros to exe.
Could you please?
An UltraEdit macro can't be converted into an executable. The UltraEdit macro commands can be executed only by UltraEdit.
But it is possible to run an UltraEdit macro from within a batch file using UltraEdit to automate file reformatting tasks using an UE macro.
Here is a commented example for such a batch file:
#echo off
rem Get name of UltraEdit executable with full path from Windows registry.
set "UltraEditEXE="
call :GetFileNameUE "HKLM\Software\Microsoft\Windows\CurrentVersion\App Paths\uedit32.exe"
if not "%UltraEditEXE%" == "" goto RunMacro
call :GetFileNameUE "HKLM\Software\Microsoft\Windows\CurrentVersion\App Paths\uedit64.exe"
if not "%UltraEditEXE%" == "" goto RunMacro
call :GetFileNameUE "HKCU\Software\Microsoft\Windows\CurrentVersion\App Paths\uedit32.exe"
if not "%UltraEditEXE%" == "" goto RunMacro
call :GetFileNameUE "HKCU\Software\Microsoft\Windows\CurrentVersion\App Paths\uedit64.exe"
if not "%UltraEditEXE%" == "" goto RunMacro
echo UltraEdit is not installed most likely as no uedit*.exe found.
echo.
pause
goto :EOF
rem Run UltraEdit using Windows command start to run UE minimized with forcing
rem always an new instance of UltraEdit, opening a file and processing this
rem file with an UltraEdit macro. This instance of UltraEdit is automatically
rem exited after macro executed once on the opened file. The macro must save
rem the file before exiting. While UltraEdit is running the batch procssing
rem is continued with deleting the environment variable and then exiting
rem batch processing. See in help of UltraEdit the page with title "Command
rem Line Parameters" for details on the used UE command line parameters.
:RunMacro
start "Run UE macro" /min "%UltraEditEXE%" /fni "Path\Name of file to modify.txt" /M,E,1="Macro file with full path/Macro Name"
set "UltraEditEXE="
goto :EOF
rem This is a subroutine called up to 4 times to determine name of UltraEdit
rem executable with full path from Windows registry if UltraEdit is installed
rem at all. It assigns file name of UltraEdit with full path and with file
rem extension to environment variable UltraEditEXE on success finding the
rem registry value in registry key passed as parameter to this subroutine.
:GetFileNameUE
for /F "skip=2 tokens=3*" %%A in ('%SystemRoot%\System32\reg.exe QUERY %1 /ve 2^>nul') do (
if "%%A" == "REG_SZ" set "UltraEditEXE=%%B" & goto :EOF
)
goto :EOF
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
call /?
echo /?
for /?
goto /?
if /?
pause /?
reg query /?
rem /?
set /?
start /?