The Batch file has been around for a long long time and although it is an old concept I still find myself dabbling in it from time to time. You can say what you want about Batch scripting but it is a tried and true method and that’s probably why we still see it in use today for automating some tasks.
Batch scripting is good and has it’s time and place but it also has some drawbacks. I won’t dive into them all here in this post but one of the bigger ones in my mind is the inability to do some kind of looping effectively.
The For command in batch conditionally performs a command several times. This works but it’s implementation is not especially kind. I thought I would share a snippet of code that I think is handy and that I seem to use regularly in some of my Batch scripts that I write for installing and configuring applications. This snippet uses the aforementioned For command and it helps avoid hard coding a file path.
echo Finding Admin.exe... c: cd \ for /f "delims=" %%i in ('dir Admin.exe /b /s') do set path2admin=%%i if "%path2admin%"=="" ( set EXITCODE=1 set EXITMESSAGE=Failed to find Admin.exe, exiting... echo %EXITMESSAGE% && goto end ) echo Run the Admin.exe at the path found... "%path2admin%" /p /n set EXITCODE=%ERRORLEVEL% set EXITMESSAGE=An unexpected error occurred, exiting... if %EXITCODE% NEQ 0 echo %EXITMESSAGE% && goto end set EXITCODE=0 :end endlocal exit %EXITCODE%
This code is fairly straight forward, it searches the C: drive for Admin.exe. If Admin.exe is found the full path is saved to a variable called path2admin. The script then executes the executable Admin.exe at the location it was found in (eg. c:\Windows\Temp\Admin.exe), if Admin.exe is not found the script exits with an exit code of 1.
Leave a Reply