Deciphering "Make EXE from BAT" Script written by Jason Faulker - batch-file

I came across a way to convert my .bat with dependencies on tool to an .exe file. However when I try using the script and run the .exe created, I always getting an error. Seems I modified the script incorrectly.
Anyone can help, please?
Here's the code with my modifications:
#ECHO OFF
ECHO Make EXE From BAT
ECHO Written by: Jason Faulkner
ECHO SysadminGeek.com
ECHO.
ECHO.
REM Usage:
MakeExeFromBat BatFileToConvert -bat MyProgram.bat
REM
REM Required Parameters:
BatFileToConvert -save MyProgram
REM Source batch file to use to produce the output Exe file.
REM
REM Optional Parameters:
IncludeFile -include Tool.exe
REM Additional files to include in the Exe file.
REM You can include external tools used by the batch file so they are available on the executing machine.
SETLOCAL
REM Configuration (no quotes needed):
SET PathTo7Zip=C:\Desktop\
REM ---- Do not modify anything below this line ----
SET OutputFile="%~n1.exe"
SET SourceFiles="%TEMP%\MakeEXE_files.txt"
SET Config="%TEMP%\MakeEXE_config.txt"
SET Source7ZFile="%Temp%\MakeEXE.7z"
REM Remove existing files
IF EXIST %OutputFile% DEL %OutputFile%
REM Build source archive
ECHO "%~dpnx1" > %SourceFiles%
:AddInclude
IF {%2}=={} GOTO EndInclude
ECHO "%~dpnx2" >> %SourceFiles%
SHIFT /2
GOTO AddInclude
:EndInclude
"%PathTo7Zip%\7za.exe" a %Source7ZFile% #%SourceFiles%
REM Build config file
ECHO ;!#Install#!UTF-8! > %Config%
ECHO RunProgram="%~nx1" >> %Config%
ECHO ;!#InstallEnd#! >> %Config%
REM Build EXE
COPY /B "%PathTo7Zip%\7zsd.sfx" + %Config% + %Source7ZFile% %OutputFile%
REM Clean up
IF EXIST %SourceFiles% DEL %SourceFiles%
IF EXIST %Config% DEL %Config%
IF EXIST %Source7ZFile% DEL %Source7ZFile%
ENDLOCAL

This doesn't really convert a bat file to an exe. It just creates a selfextracting archive (exe) which contains the bat file. On execution it extracts the file to a temporary folder and runs it from there. You can even extract the bat from the exe just by using 7zip/rar/winzip or any other archiver.
If you want to convert a bat to an exe for real you should use one of the tools from the web (like this one: http://www.f2ko.de/index.php?lang=en) or concider using a simple script language like AutoIt.
If you pick the second, you can simply execute your bat code with Run("put your bat code in here") and you can compile your script to a "real" exe file.

For an alternative approach, you can basically do the same thing as described in the accepted answer (making a 7z-SFX) with WinRAR. That way, you can also do it with a GUI, and I will try to add some more useful information.
Actually, you can also use the latter approach to generate portable applications and it also works with "converting" every runnable (or openable) file into an .exe.
If you need that "portability hack", you should unpack your .exe or .msi installer with Universal Extractor. Details can be found in this Article, Step 1 to 4. Newer Versions of 7zip or WinRAR also come with comparable features.
Now you add all needed files to the archive. In the easiest case, this is just your .bat script or whatever file you want to "convert" into an .exe applivation. (Step 5 here)
Steps 6 and 7 are just some Settings for the SFX-Archive, 8 is the interesting one, as you select what you actually want to run there. Input the name of your (.bat-)file.
Step 9 lets you select where to unpack to - you do this setting manually and programmatically in the MakeExeFromBat.bat-script.
After this process you created a Portable App in SFX archiever form, enjoy
The word "converting" was put into quotation marks, because running that .exe actually works like this:
The contents of the (SFX-)EXE file are extracted from the "archive part" to a directory as the specified temp directory.
( The config file generated by the script is read. )
The file, that was previously contained in the EXE file and then extracted, is now executed in a new window.
a) This file could besides a .bat be anything - as e.g. an image, a MP3 or a video
b) or also a Python Script (of course your OS needs to know how to deal with that file.
Once finished, the temp files are removed.
You can also derive some limitations from that. If you have a .bat that needs the content of the working directory, you will have a problem. (Say, a batch that renames all files in the current dir from 1 to n.) In some cases that can be dealt with by adding all needed files to the archive too. On Windows Vista and all newer OSes, you might encounter a message box after the script is run. After selecting ‘This program installed correctly’, the message box will not be displayed in the future for this file. Because the EXE file launches in a new window, the typical way of logging output (using the > char) will not work as expected. In order to log the output, you would need to handle this natively in your source script.
All references were already linked, but once again: Big credit goes to Jason Faulkner for providing the Article and 7zip-Approach, binbert for the WinRAR-SFX Solution (which is as hinted much more versatile -> portability) and some credit to creative8 for finding the two and the article comparing them.

Actually, I was develping another solution using AutoHotkey. In my case, I just want to be able to add my .bat to the windows start menu - but the options are not limited to that.
The script itself is just a oneliner and .AHK is easily converted to .exe (I used v1.1.33.09):
run % SubStr(A_ScriptName, 1, -4) ;// run also has the option to run your file minimized or hidden, see the source 2 below
Source 2
What it does is taking its own name, removing the .ahk or .exe respectively (the last 4 characters, hence -4) and running excactly that. Usage could not be easier: you have a runme.bat, so you rename the program I provide to runme.bat.exe. Say you want the .exe to open an image.png - guess what, rename it to image.png.exe. You get the gist - that's it. It dynamically checks its name to find what to run. In my opinion, this is not much less mighty than "unpacking the .bat and then run it", but (again imho) it is much more elegant.
Use it as you wish, I should probably start a public github page or so.

Related

Running ant commands using batch file

Currently this is how I have written the code in the batch file:
C:\ cd C:\abc\xyz\build-scripts-master
call setEnv.cmd
cmd ant do-clean
cmd ant do-dist
This is not working. It just executes the setEnv and breaks out. It does not run the remaining commands
Manually this is how it works:
I first go to the folder C:\abc\xyz\build-scripts-master through the Command Prompt
Then I type in setEnv, which is a windows command script, and hit return.
Then I type in ant do-clean
And then ant do-dist
I want to automate this process and hence was trying to achieve this using batch file.
Try the following:
#CD /D "C:\abc\xyz\build-scripts-master"
#Call setEnv.cmd
#Call ant.bat do-clean
#Call ant.bat do-dist
The latter two lines assume that ant.bat is located somewhere in the current working directory or %PATH%
It is not imperative that the directory path is doublequoted in this case, just good practice.You could continue not to use the .bat extension with ant. I've included it just to make it clear that it is a batch file, and should be Called in the same way as the setEnv batch file.
it didn't run the bat files because you didn't specify the files' location in the code. As it stands right now, the script expects the .bats to exist in the working directory or it has been placed in the folder. The only way it will run the files arbitrarily is if you had placed your working location in the system variables or set the Path to the folders location. I don't know if the cmd and call are needed. I have never used them in my scripts.

Using wild cards in windows with directories

I am running a Jenkins project which runs under Windows. I have a dir to find a file (html file) from my directory. This shows up
reports\All Smoke_2018-01-23T084148.270-0600\TestLog.html
I know the first directory will always be "reports" and the file name will be TestLog.html. However, the middle directory (All Smoke_2018-01-23T084148.270-0600) will depend on the date and time. So what I want to do is
echo "some string" >> reports\*\TestLog.html
it will actually be more complicated than that. But it does not appear to allow me to use an * as a directory name (as Unix would).
Is there another way to refer to the file? I know find has /s which is how I find it and findstr also has a /b. But how can I get the file name to echo to it?

Batch File To Get It's Own Directory Or The Directory Defined In The "Start In" Property Of A Shortcut

I am writing a batch file on my Windows 8.1 machine. In one section of my batch file I need to start a command prompt in the "current working directory".
So far, this is what my batch file looks like:
#echo OFF
set WORKING=%cwd%
start cmd.exe /K pushd %WORKING%
exit
Let's say the batch file is located in the folder C:\Temp\Utilities. If I open an explorer window and double click the batch file to run it everything works great. A new command prompt is created in the directory C:\Temp\Utilities. However, if I right-click the batch file and select Run as administrator the working directory is no longer the location of the batch file, it's C:\Windows\System32.
Similarly, if I create a shortcut to the batch file in a different folder (for example. C:\Temp) and repeat the two steps above the results are the same. If I double click the shortcut and run it as a normal user the working directory is what I would expect. (Note, the working directory for the shortcut it's whatever is set for "Start in" of the shortcut properties, not the location of the batch file.) If I right click the shortcut and run it as administrator I again get a command prompt opened to the folder C:\Windows\System32.
I assume this is a "bug" or "feature" (if you want to call it that) in Windows 8.1 and it probably happens because execution environments for programs run as administrator are forced to run in the System32 folder? (I remember with Windows 7 this did not happen so it must be a new feature to Windows 8.)
I found one way to fix the issue and stop the command prompt from starting in C:\Windows\System32. I did this by modifying the following line in the batch file:
set WORKING=%~dp0
Doing it this way sets the working directory to the location of the batch file. With this change, no matter how I run the batch file or the shortcut (administrator or normal) the working directory ends up being the same, C:\Temp\Utilities.
The problem with this solution is I don't want the working directory to always be the location of the batch file. If the batch file is run directly then it's okay but if I run it from a shortcut I need the working directory to be whatever is set in the "Start in" property of that shortcut. For example, if the batch file is located in the folder D:\Temp\Utilities this is what I need to happen regardless of whether I run as administrator or not:
Shortcut Location Start In Property Command Prompt Working Directory
-------------------- ------------------- ------------------------------------------
C:\Temp <undefined> D:\Temp\Utilities
C:\Data\bin C:\Data\bin C:\Data\bin
C:\Data\bin D:\Temp\Utilities D:\Temp\Utilities
What this means is I can't always use %~dp0 to set the working directory in my batch file. What I need is some way for the batch file to know if it was run either directly or by a shortcut. If the batch file is run directly then the working directory is easy to get, it's just the value of %cwd%. If the batch file is run by using a shortcut, I don't know how to get the "Start in" property inside the batch file.
Does anyone know how I can do these two things inside my batch file:
1. Check whether it was run directly or by a shortcut.
2. If run by a shortcut, get the "Start in" property of the shortcut that started it.
Thank you,
Orangu
UPDATE
I found sort-of a "hackish" way to fix the issue. For the shortcut I edited the "Target" field and changed it to the following:
cmd.exe /k pushd "C:\Temp" && "D:\Temp\Utilities\batchfile.bat"
Now the working directory can be obtained by calling %CD% in the batch file and this works for both administrator and normal users. It does not, however, work for the case when I run the batch file directly. I still need to use %~dp0 in that case.
I don't like this solution, however, because it requires me to manually change all shortcuts I make and it also makes the icon look like a cmd prompt icon rather than a batch file.
Have you already considered to not use shortcuts at all?
You could e.g. create a batchfile_exec.bat containing your call
REM optionally do
REM cd /D working_directory
REM if you want to force a special working directory
D:\Temp\Utilities\batchfile.bat
and replace all the shortcuts with batchfile_exec.bat. If you double-click batchfile_exec.bat, the working directory will be the one containing batchfile_exec.bat.
I personally don't like Windows shortcuts that much, because they are hard to handle within a revision control system. As you also noticed, it is very time consuming if you want to modify a lot of them.
By the way: If batchfile.bat was designed/written to be always run from the direcory where it is located, you might also consider to modify batchfile.bat to force that behaviour:
setlocal
cd /D %0\..
REM your original content
endlocal
In %0 the path to the batchfile is stored.
The trick is to assume that %0 is a directory and then to change one level lower based on that directory. With /D also the drive letter is changed correctly.
The cd command doesn't care if %0 is really a directory. In fact %d doesn't even have to exist (%0\dummy\..\.. would also work).
The setlocal command is to have the working directory being restored when batchfile.bat has finished (this would be good if batchfile.bat was called form another batch file).
I noticed that the endlocal command is not really necessary in this context since it is applied implicitly when batchfile.bat finishes.

batch language tutorials - running simple programs that rely on .bat file

I am just starting to get a handle on batch programming.
To date, I've been copy/pasting into the MS-DOS command prompt from a text editor. Some of these copy pastes are getting large. Im sure there is a better way to go about this, ie. writing a line in command prompt that calls other text files (effectively doing the work of copy pasting).
Are these external files going to be .bat (which are just text that could also be put directly into the command prompt?) or .txt or something else?
I am mainly looking into this so that I can get into reusing code and getting into looping.
Are there any tutorials someone would recommend to get my acquainted with these topics?
Thanks for any help.
You can name a text file .bat or .cmd (the latter if you know it's only usable as a Windows batch file) and put commands into it, line by line.
You can run such files by typing their name at the command prompt when you're in the directory where they reside (or if they are contained in one of the PATH directories).
By default the behavior will match pretty much exactly with what you would type by hand. You'll see what commands are executed as well as their output. For example the following batch file (saved as test.cmd here)
echo Hello World
dir /b *.cmd
yields the following output when run
> echo Hello World
Hello World
> dir /b *.cmd
date.cmd
foo.cmd
test.cmd
x.cmd
y.cmd
You can suppress the output of the command being run by including the line
echo off
in your batch file. Prefix it with an # to suppress command output for that line in particular, but ever subsequent command won't be echoed:
#echo off
If other concrete questions arise, feel free to ask.

Help with Batch Files?

What are batch files useful for? They just seem to be used to make viruses and other things...but it seems like shell scripting to me.
Whats the uses for batch files?
From Batch file article at Wikipedia:
Batch files are useful for running a
sequence of executables automatically
and are often used by system
administrators to automate tedious
processes. Unix-like operating
systems (such as Linux) have a similar
type of file called a shell script.
A simple example:
for /f "tokens=* delims=" %%i in ('dir /s /b /a:d *svn') do ( rd /s /q "%%i")
If you save the above line in a file called ClearSVNFolders.bat and after that execute a double click you'll delete every folder named svn that resides inside a root path...
You automated the whole process. You could easily spend hours doing the above task if you had a deep root directory, that is, one containing thousands of folders. :)
Batch files are the Windows equivalent of a Unix shell script. So you can use them to automate things.
You could use them for shell scripting. :-P
Of course, they kind of suck at that, compared to bash (or perl/python/tcl). But if you're on Windows, it's a one-horse race unless you want to install cygwin or msys and battle with Unix/Windows incompatibilities.
Batch Files are extremely useful. They are super easy to learn as well. you can make them do things on startup like say that a program wants to open itself and wont close even from taskman.exe you can force it to shutoff without warning.
or you could make games and ineractive things like i like to do.
i have a Messenger that i made with fully customizable colors and accounts with account management and servers.
But you probably dont trust me enough for you to download it.
But yea they are pretty useful.
Batch file is "a computer file containing a list of instructions to be carried out in turn."
We have been studying since childhood that computer is a dummy machine and this is a method of instructing a dummy machine.
For example :-
If you want to instruct the system to create a folder with random name then type ,
#echo off
md %random%
Creating Batch files enables you to execute several line of CMD commands in a single file.
For example :-
#echo off
md %random%
tasklist
Pause
The entire purpose of a Batch script is to execute several DOS commands in sequence:
echo Hello!
set var=7
echo I just made var=%var%!
pause
It was invented in MS-DOS for user simplicity to execute things they did all the time, the most notable thing being "AUTOEXEC.BAT" which started once the command interpreter started, people would add things like:
echo Welcome to my computer!
or
cd C:\Games\
To make it quicker to access their games or whatever they needed.

Resources