blocking an if statement error message from a batch file - batch-file

I am trying to design a batch program that scans the D:\ on my computer for a CD album and then opens a program to play it. I don't want to use Autoplay because want to design my own custom program for the purpose. I am using an IF statement and a GOTO statement that loops back to the IF statement after a delay. Here is what I have:
:rescan
if exist D:\Track01.cda start (my soon-to-be music playing program)
timeout 2 /NOBREAK
goto rescan
The problem is that if there is no CD in the drive, the IF statement causes a seprate error message window to pop up.
Is there any way to block this message?

I do not think there is a way to block this message as it is occurring outside of the control of your batch file. However I checked the existence of the drive before entering the loop and this seemed to work for my tests.
IF EXIST D:\ GOTO rescan
echo Drive does not exist
goto end
:rescan
if exist D:\Track01.cda echo start (my soon-to-be music playing program)
timeout 6 /NOBREAK
goto rescan
:end
Hope it helps you out.

use another command:
dir D:\track01.cda 1>nul 2>&1 && start (your program)
If there is no disk, dir returns The device is not ready. and an %errorlevel%of 1. If there is a disk, but no audio-disk (no "track01.cda"), dir returns "File not found" and an %errorlevel%of 1
(All output of dir is redirected to nul to keep the screen clear - change that, if you want that output).
&& works as "if previous command was successful then" ("if %errorlevel% is not 0")

Related

Batch - If an Audio File is Not Playing is it Considered a Task?

I have been working on a project idea today, and I encountered this issue while attempting to kill an audio task. Here's my code (Problem is after the code block):
:two
ECHO Reading...
start C:\Users\Gigabyte\Documents\Audacity\FDD.wav
timeout /t 24 >nul /nobreak
taskkill FDD.wav
GOTO continue
:three
ECHO Reading
start C:\Users\Gigabyte\Documents\Audacity\HDD.wav
Timeout /t 44 >nul /nobreak
taskkill HDD.wav
:continue
It gave me an error that something was invalid then shut the window. I usually am able to read it word by word but time has taken it's toll on me. All I know is that something in quotes is invalid as of right now. However, I have suspicion that the audio file name is invalid and no such task exists. And this goes back to the main question. 'If an Audio File is Not Playing is it Considered a Task?'.
(If it's a matter of task or process ID's then how do I find them?)
(If you need some more code to find out the context of the situation I'll gladly add some)
Audio files are data files, not executables. You need to find the program that is actually playing the audio file and kill it instead. So if you were using Windows Media Player then kill that. (Groove Music not included)
-SomethingDark

Why does command START used in a batch file not start a batch file?

I made a Main batch file with the lines below:
#echo off
color 1e
title ------ Just a Test ------
start "C:\Users\%USERNAME%\Desktop\Check.bat"
:START
echo Welcome to the Game!
...
And Check.bat contains:
#echo off
if not exist "C:\Users\%USERNAME%\Desktop\Batch_System\importantFile.dll" goto ERROR
if exist "C:\Users\%USERNAME%\Desktop\Batch_System\importantFile.dll" goto CONTINUE
:ERROR
cls
echo ERROR :
echo Important file not found. please reinstall the program
pause
exit /b
:CONTINUE
cls
exit /b
When I use the command start, it starts only a command prompt with the Check.bat directory and the main batch file continues executing the game. I want to force close the main batch file if importantFile.dll doesn't exist.
Okay, let me explain: When the main batch file is executed and runs the command start to start another batch file called Check.bat, the file Check.bat checks if the file importantFile.dll exists, and if not, Check.bat displays an error message.
Does anyone know how to write Check.bat in a manner that when the .dll file does not exist, force the main batch file to exit?
First, help on every command can be get by running in a command prompt window the command with /? as parameter. start /? outputs the help of command START. call /? outputs the help of command CALL usually used to run a batch file from within a batch file. Those two commands can be used to run a batch file as explained in detail in answer on How to call a batch file that is one level up from the current directory?
Second, the command line
start "C:\Users\%USERNAME%\Desktop\Check.bat"
starts a new command process in foreground with a console window with full qualified batch file name as window title displayed in title bar at top of the console window. That is obviously not wanted by you.
Third, the Wikipedia article Windows Environment Variables lists the predefined environment variables on Windows and their default values depending on version of Windows.
In general it is better to use "%USERPROFILE%\Desktop" instead of "C:\Users\%USERNAME%\Desktop".
There is no C:\Users on Windows prior Windows Vista and Windows Server 2008 by default at all.
The users profile directory can be on a different drive than drive C:.
It is also possible that just the current user's profile directory is not in C:\Users, for example on a Windows server on which many users can logon directly and for which the server administrator decided to have the users' profile directories on a different drive than system drive making backup and cleaning operations on server much easier and is also better for security.
Well, it is also possible to have the user's desktop folder not in the user's profile directory. But that is really, really uncommon.
Fourth, on shipping a set of batch files, it is recommended to use %~dp0 to call other batch files from within a batch file because of this string referencing drive and path of argument 0 expands to full path of currently executed batch file.
The batch file path referenced with %~dp0 always ends with a backslash. Therefore concatenate %~dp0 always without an additional backslash with another batch file name, folder or file name.
See also What is the reason for batch file path referenced with %~dp0 sometimes changes on changing directory?
Fifth, I suggest following for your two batch files:
Main.bat:
#echo off
color 1e
title ------ Just a Test ------
call "%~dp0Check.bat" || color && exit /B
echo Welcome to the Game!
Check.bat:
#echo off
cls
if exist "%~dp0Batch_System\importantFile.dll" exit /B 0
echo ERROR:
echo Important file not found. Please reinstall the program.
echo/
pause
exit /B 1
The batch file Check.bat is exited explicitly on important file existing with returning exit code 0 to the parent batch file Main.bat. For that reason Windows command processor continues execution of Main.bat on the command line below the command line calling the batch file Check.bat.
Otherwise Check.bat outputs an error message, waits for a pressed key by the user and exits explicitly with non zero exit code 1. The non zero exit code results in Main.bat in executing the next command after || which is COLOR to restore initial colors and next executing also EXIT with option /B to exit the execution of Main.bat.
See also:
Single line with multiple commands using Windows batch file
What are the ERRORLEVEL values set by internal cmd.exe commands?
Which cmd.exe internal commands clear the ERRORLEVEL to 0 upon success?
Where does GOTO :EOF return to?
exit /B without an additionally specified exit code is like goto :EOF.
The CALL command line in Main.bat could be also written as:
call "%~dp0Check.bat" || ( color & exit /B )
And Main.bat could be also written as:
#echo off
color 1e
title ------ Just a Test ------
call "%~dp0Check.bat"
if errorlevel 1 (
color
goto :EOF
)
echo Welcome to the Game!
I do not recommend using in Main.bat just EXIT instead of exit /B or goto :EOF. Just EXIT would result in exiting the current command process independent on calling hierarchy and independent on how the command process was started: with option /K to keep it running to see error messages like on opening a command prompt window and next running a batch file from within command prompt window, or with /C to close the command process after application/command/script execution finished like on double clicking on a batch file.
It is advisable to test batch files by running them from within an opened command prompt window instead of double clicking on them to see error messages on syntax errors output by cmd.exe. For that reason usage of just EXIT is counter-productive for a batch file in development. Run cmd /? in a command prompt window for help on Windows command processor itself.
Last but not least see:
Microsoft's command-line reference
SS64.com - A-Z index of the Windows CMD command line
start is asynchronous by default. Use start /wait so that main.bat can test the exit code of check.bat. Make check.bat return an appropriate exit code.
For example...
main.bat
#echo off
start /b /wait check.bat
if not %errorlevel% == 0 exit /b
echo "Welcome to the game!"
...
check.bat
#echo off
if exist "importantfile.dll" exit 0
echo ERROR: Important file not found. Please reinstall the program.
pause
exit 1
notes
Added /b to start to avoid opening another window. Change that per your preference.
You could use call instead of start but call gives the called code access to the variables of main.bat so encapsulation is improved if you use start as you did.
The logic in check.bat is simplified above. Once you identify the success path early in the script and exit, the rest of the script can assume the fail path. This saves you a few if's and labels which you might find simplifies writing and reading of similar scripts. Beware of potentially confusing multiple exit points in longer scripts though!
When choosing exit codes, 0 is a common convention for success.
The above code is just one technique - there are several other options (such as checksomething && dosomethingifok). Some useful information on return codes, and checking them, can be found in http://steve-jansen.github.io/guides/windows-batch-scripting/part-3-return-codes.html
Thanks to the answer from Mofi. I've my example and exp. on this. To be short, it's about the setting of log date format. You may change the format of time , date and log. you may have the result.
why-batch-file-run-with-failure-in-windows-server

How to evaluate exit code of an application started from within a batch file?

I am trying to execute an application from a batch file by using START command (to hide console when executing) and I need to get errorlevel after execution. For example after System.exit(10) I'd like to restart Java application:
:while
START javaw ...
IF errorlevel 10 GOTO while
But it doesn't work because errorlevel condition is evaluated before the java process has finished.
I've also tested the next code but I get an empty text file because of the same reason:
:while
start javaw ... >exit.txt 2>&1
set /p status=<exit.txt
if "%status%"=="10" goto :while
Then, is there any way to launch a Java application, without console (/WAIT is not an option), and using a loop to restart the app when a problem occurs?
See answer on question How to call a batch file in the parent folder of current batch file? to understand the 4 different methods on running an application or batch file from within a batch file.
And see also Difference between java/javaw/javaws.
The execution of the batch file results already in opening a console window.
Therefore I suggest to use simply
:while
java.exe ...
IF errorlevel 10 GOTO while
Or use following code if you don't want to see any output by the Java application in console window of the batch file:
:while
java.exe ... 1>nul 2>nul
IF errorlevel 10 GOTO while
1>nul redirects output written to stdout to device NUL and 2>nul redirects the error messages written to stderr also to device NUL.
The only solution I can think of running a Java application without displaying a console window and additionally check successful execution of the Java application would be to write a Windows (GUI) application in C/C++/C# which does not open a window like javaw.exe and which runs javaw.exe with the appropriate parameters as process with evaluating the return code.
But with a batch file it is impossible to avoid opening a console window completely as far as I know. The console window can be opened minimized, but not hidden completely.
using this solution: Windows batch assign output of a program to a variable you can do something like this:
#echo off
:loop
application arg0 arg1 > temp.txt
set /p status=<temp.txt
if "%status%"=="10" goto :loop
echo "Done."

How to automatically close App_A when I close App_B using batchfile

Hi everyone I'm a newbie in batchfiling but loved tinkering and coding every other time. Can I make a batch file that closes two program simultaneously? Example, I created a batchfile that opens two program, App_A (gamepad imulator) is minimized App_B (offline RPG Game) normal window. What I want is when I close App_B App_A would automatically close too so that I don't have to restore the window and manually close the imulator.
this is the code I just did which I also found in this site and got it working:
ECHO OFF
start /d "C:\Documents and Settings\Computer\My Documents\Imulator\PROFILE" SET1.imulatorprofile /m
ECHO IMULATOR STARTED
start /d "C:\Program Files\App_B" App_BLauncher.exe
ECHO APP_B STARTED
ECHO OPERATION COMPLETE
Any comments or suggestions is GREATLY APPRECIATED! THANKS in ADVANCE :)
You can use another batch file with two taskkill lines, one for each of your apps, and launch that.
Otherwise you'd need to have a batch file running all the time in a window, which loops and checks if appB is not running and then it will close appA. It's not very elegant.
I'm not very good using the windows commandline, but I would try the following approach:
start imulator (which should quit automatically after APP_B exited)
start APP_B (using the /wait option - this should pause the batch processing)
kill imulator (using PsKill by name)
You can find details about start, PsKill and other commands at this site.
Hope that helps a bit.
*Jost
...added later...
Another option would be to do regular checks in the background if a process (App_B) is running and continue (with stopping App_A) when it is finished. This approach makes sense when App_B is only a launcher for another process (e.g. App_Launched_By_B) and comes back directly.
This can be done with a small loop which might look similar to this one:
start "App_A" /d "C:\Programs\App_A" App_A.exe
ECHO App_A STARTED
start "App_B" /d "C:\Programs\App_B" App_B.exe
ECHO App_B STARTED
ECHO GIVE App_B 30 SECONDS TO LAUNCH App_Launched_By_B
SLEEP 30
:LOOP
PSLIST App_Launched_By_B >nul 2>&1
IF ERRORLEVEL 1 (
GOTO CONTINUE
) ELSE (
ECHO App_Launched_By_B IS STILL RUNNING - PAUSE ANOTHER 5 SECS
SLEEP 5
GOTO LOOP
)
:CONTINUE
PsKill App_A
ECHO App_A STOPPED
This example came originally from another answer and was written by aphoria. I adapted it just a little little bit for this case.
Additional information about PsList and other commands can be found at this site.
I also want to note that I do not really like this approach, because it consumes some cpu without doing much. But it is the only solution from a batch file I can see.

bat file. delete until success?

I run a bat file to clean up and sometimes it takes a few seconds for my app to full close. In it i delete a database. Instead of waiting or running it multiple times i would like the bat file to continue its attempts until it has a success. How can i do that?
goto :foo2
:foo
sleep 1
:foo2
del file
if exist file goto :foo
In this code, you rely on the fact that your command sets non zero error level if (when) it fails. And you know which error code it sets.
Something along the lines of
#echo off
:Delete
deletedatabasecommand
if ERRORLEVEL 123 GOTO Delete
That should do it.

Resources