How to close cmd window with command? - windows

I make a program on cmd with 2 windows and I want to close one cmd window with a command.
if %choise%==1 goto menu
:menu
cls
color a
echo ===============================
echo MENU
echo ===============================
echo 1.Eixt 2.History
echo.
set /p choise=Choose:
if %choise%==1 exit
if %choise%==2 goto History
can anyone help?

I want to close one cmd window with a command
rem if %choise%==1 goto menu
The above line will cause an error if %choise% is not defined so remove it.
goto was unexpected at this time.
Use the following batch file:
#echo off
:menu
cls
color a
echo ===============================
echo MENU
echo ===============================
echo 1.Exit 2.History
echo.
set /p choise=Choose:
if %choise%==1 exit
if %choise%==2 goto History
endlocal
If you press 1 the batch file will exit the cmd shell
If you press 2 you will get an error as there is no label history
The system cannot find the batch label specified - History
I have two windows, "MWprog" and "History Box"
I want to close the "History box" window without closing the "MWprog" windows.
Add the following command to the batch file:
taskkill /f /fi "WINDOWTITLE eq Administrator: History Box"
Note:
The extra space - there are two after the : - is required.

To exit a batch use goto :eof [End of File]
if "%ShouldIExit%"=="TRUE" goto :EOF
or
if "%ShouldIExit%"=="TRUE" exit
or
if "%ShouldIExit%"=="TRUE" exit 2
Rem exit 2 will set the errorlevel to 2, and exit the program.
or
Search for this program on your computer, usually deep in the windows directory.
TaskKill.exe

Related

Issue concerning path input in .bat menu

Hi I am trying to make a small menu in which the .bat file uses the user input to define a path. The code below works.
#ECHO OFF
SET /P var= Type The FULL Path In Here:
MKDIR %var%\
pause
However when I try to implement the code into the menu below. It fails and I can't read the error because it immediately exits the batch file. I am running a windows 10 machine and running the batch from the C:\ drive. The batch file makes the folders on the C:\ drive as well. I would be grateful for any help Thanks.
ECHO OFF
CLS
:MENU
ECHO.
ECHO ...............................................
ECHO PRESS 1 to select your task, or 2 TO EXIT.
ECHO ...............................................
ECHO.
ECHO 1 - Set Path
ECHO.
ECHO 2 - EXIT
ECHO.
SET /P M=Type 1 or 5 then press ENTER:
IF %M%==1 GOTO CallScript1
IF %M%==5 GOTO EOF
CallScript1
#ECHO OFF
SET /P var= Type The FULL Path In Here:
MKDIR %var%\
GOTO:EOF
You are missing the colon before the label CallScript1 on line 17
i.e. replace
CallScript1
with
:CallScript1

Execute batch code when user click on exit

I am working on some code testing, and I stumbled on a problem I can't find or fix. My problem is:
If a user accidentally closes the cmd window, I'd like to execute a batch code before it actually closes. For example:
I run script A.bat . When a user wants to exit, I want it to delete my B.bat and then close the window.
This is how the code may look like:
#ECHO OFF
echo Welcome to A.bat
del B.bat (when user exits the window)
I couldn't find it on google and forums, so I thought maybe you guys could help me out. Thanks in advance, Niels
This works for me:
#ECHO OFF
if "%1" equ "Restarted" goto %1
start "" /WAIT /B "%~F0" Restarted
del B.bat
goto :EOF
:Restarted
echo Welcome to A.bat
echo/
echo Press any key to end this program and delete B.bat file
echo (or just close this window via exit button)
pause
exit
EDIT: Some explanations added
The start command restart the same Batch file in a new cmd.exe session; the /B switch open it in the same window and the /WAIT switch makes the original file to wait until the new one ends. The new Batch file must end with exit in order to kill the new cmd.exe session (because it was started with the /K switch). No matters if the new cmd.exe session ends normally because the exit command or because it was cancelled with the red X; in any case the control returns after the line that started it in the original execution.
I've had to do something similar to what you're describing. I'm not sure whether this is the simplest or most efficient way to accomplish what you ask, but it does indeed work nevertheless.
#echo off
setlocal
:lockFile
rem // create lock file to inform forked helper thread when this thread completes
rem // credit to dbenham: http://stackoverflow.com/a/27756667/1683264
set "lockFile=%temp%\%~nx0_%time::=.%.lock"
9>&2 2>NUL (2>&9 8>"%lockFile%" call :main %*) || goto :lockFile
del "%lockFile%"
exit /b
:main
call :cleanup_watcher "B.bat"
rem // put your main script here
pause
goto :EOF
:cleanup_watcher <file> (<file> <file> etc.)
rem // Write external script to delete filename arguments
rem // (so if main script exits via ^C, temp files are still removed)
>"%temp%\tmp.bat" (
echo #echo off
echo setlocal
echo :begin
echo ping -n 1 -w 500 169.254.1.1 ^>NUL
echo del /q "%temp%\%~nx0*.lock" ^>NUL 2^>NUL
rem // If lockfile can't be deleted, the main script is still running.
echo if exist "%temp%\%~nx0*.lock" goto :begin
echo del /q "%temp%\tmp.bat" %* ^&^& exit
)
rem // fork cleanup watcher invisibly to catch ^C
>"%lockfile%.vbs" echo CreateObject("Wscript.Shell").Run "%temp%\tmp.bat", 0, False
wscript "%lockfile%.vbs"
del "%lockfile%.vbs"

Batch files can not supress "terminate job"

Im trying to open a 2nd batch file and detect if it normally exited or closed by a user (ctrl+c or x or window termiate etc..)
so Im using this following example by Batch run script when closed
#Echo off
set errorlevel=1
start /w %comspec% /c "mode 70,10&title Folder Confirmation Box&color 1e&echo.&echo. Else the close window&pause>NUL&exit 12345"
echo %errorlevel%
pause
Im trying to keep 1st batch waiting (/W) since I will check for errorlevel later on
But after closing the 2nd batch file I get an error like ^cterminate batch job (Y/N)?
I tried the suggestion over https://superuser.com/questions/35698/how-to-supress-terminate-batch-job-y-n-confirmation
with the script
rem Bypass "Terminate Batch Job" prompt.
if "%~2"=="-FIXED_CTRL_C" (
REM Remove the -FIXED_CTRL_C parameter
SHIFT
) ELSE (
REM Run the batch with <NUL and -FIXED_CTRL_C
CALL <NUL %1 -FIXED_CTRL_C %*
GOTO :EOF
)
That works quite fine
So is there a way of starting from same batch file and avoiding the terminating?
Or do I have to create a new batch from same batch and call it?
(I don't want them to see the file aswell)
Do not assign values to a volatile environment variable like errorlevel using set command. Doing that causes it becomes unvolatile in current context.
Always use title in START "title" [/D path] [options] "command" [parameters].
start "" /W cmd /c "anycommand&exit /B 12345" always returns 12345 exit code. It's because all the cmd line with & concatenated commands is prepared in parsing time (the same as a command block enclosed in parentheses) and then run entirely, indivisibly. Omit &exit /B 12345 to get proper exit code from anycommand, or replace it with something like start "" /W cmd /c "anycommand&&exit /B 12345||exit /B 54321" to get only success/failure indication.
Next code snippet could help:
#ECHO OFF
SETLOCAL enableextensions
set "_command=2nd_batch_file.bat"
:: for debugging purposes
set "_command=TIMEOUT /T 10 /NOBREAK"
:: raise errorlevel 9009 as a valid file name can't contain a vertical line
invalid^|command>nul 2>&1
echo before %errorlevel%
start "" /w %comspec% /C "mode 70,10&title Folder Confirmation Box&color 1e&echo(&echo( Else the close window&%_command%"
echo after %errorlevel%
Output shows sample %_command% exit codes: 0 or 1 if came to an end properly but -1073741510 if terminated forceably by Ctrl+C or Ctrl+Break or red ×
==>D:\bat\SO\31866091.bat<nul
before 9009
after 0
==>D:\bat\SO\31866091.bat<nul
before 9009
after 1
==>D:\bat\SO\31866091.bat<nul
before 9009
^CTerminate batch job (Y/N)?
after -1073741510
==>
This works for me:
call :runme start /w "Child Process" %comspec% /c "child.bat & exit 12345" <NUL >NUL 2>NUL
echo %ERRORLEVEL%
goto :eof
:runme
%*
goto :eof
The idea is to call a subroutine in the current script rather than calling out to an external script. You can still redirect input and output for a subroutine call.

VBScript and Batch interaction

I am running a batch script and somewhere the user has to access a database.
At this moment, a window made in vbscript would prompt asking the user to type in the login and password. (OK, Cancel buttons)
If the credentials are correct after the OK, the batch would continue according to planA, otherwise the batch would do something else going to planB. If (Cancel), it would return to the batch and the main menu.
THIS IS WHAT I HAVE BEEN STRUGGLING WITH:
#echo off
:Ini
echo [1] Access database
echo [2] Main menu
echo:
set /p Quest= What do you prefer (1 / 2)?
if not '%Quest%'=='' set Quest=%Quest:~0,1%
if '%Quest%'=='1' goto VBS
if '%Quest%'=='2' goto BATCH
echo Invalid option, please try again
cls
goto Ini
:BATCH
echo Heading for main menu ...
goto Main
:VBS
:wscript.echo InputBox("Enter your password","VBScript-Batch")
findstr "^:" "%~sf0" | findstr /i /v ":Label" >temp.vbs
for /f "delims=" %%N in ('cscript //nologo temp.vbs') do set pass=%%N
del temp.vbs
:Label1
If %pass%=="okay" echo Valid Password ! & goto PLAN-A
If not %pass%=="okay" echo Invalid Password !! & goto PLAN-B
:PLAN-A
echo continue from here
:PLAN-B
echo do something else
(...)
-- How to capture the user information, validate it and go back to the batch for the planA or planB ??
As you see, if we eliminate the "& goto PLAN" stuff the script works. It sends the VBS input "pass" to the batch and the batch echoes "continue from here" or "do something else", from where the rest of your code should continue in the same batch.
However, it is not working ... Any help to make this really work ?
Your primary issue was you didn't set up the file properly to facilitate extracting the VBS from the batch file. Your VBS looks no different than a batch label. You filter out "Label" labels, but you still include lines like :ini, :BATCH, etc. Obviously those will trip up VBS. I solved the problem by prefixing your VBS with ::: and adapting your filter. There is no need to explicitly filter out any labels. I chose 3 colons because a single colon is used for a label, and 2 colons is frequently used for comments. You could have multiple independent VBS scripts embedded within your batch simply by varying the number of preceding colons.
I also restructured the code a small amount, and sprinkled in some EXIT /B statements so that code does not fall through. Also your :MAIN is not defined so I commented out the GOTO and replaced it with EXIT /B.
#echo off
:Ini
echo [1] Access database
echo [2] Main menu
echo:
set /p Quest= What do you prefer (1 / 2)?
if not '%Quest%'=='' set Quest=%Quest:~0,1%
if '%Quest%'=='1' goto VBS
if '%Quest%'=='2' goto BATCH
echo Invalid option, please try again
cls
goto Ini
:BATCH
echo Heading for main menu ...
::goto Main
exit /b
:VBS
:::wscript.echo InputBox("Enter your password","VBScript-Batch")
findstr "^:::" "%~sf0" >temp.vbs
for /f "delims=" %%N in ('cscript //nologo temp.vbs') do set pass=%%N
del temp.vbs
If "%pass%"=="okay" (
echo Valid Password !
goto PLAN-A
) else (
echo Invalid Password !!
goto PLAN-B
)
:PLAN-A
echo continue from here
exit /b
:PLAN-B
echo do something else
exit /b

Bat and Com, file. Init Error trying to start a exe file

I am trying to run a exe from a Bat file.
The error is a popup Init Error Genre Unknown.
The game runs fine by it's self. But want to use a bat file./
What causes this? I have spent 3 days and nothing about a Init error Genre Unknown
on Google yahoo Dogpile or even webferret
I did check all the registry sites to make sure my settings are correct for Bat files.
#echo off
START "" "C:\01Game\1aedit\1aedit.exe" "-i"
rem start /wait C:\01Game\1aedit\1aedit.exe
pause
if not errorlevel 0 goto :ERR1
goto :STEP2
:STEP2
START "" "..\2atop\2atop.exe" "-i"
rem start /wait C:\01Game\2atop\2atop.exe
pause
if not errorlevel 0 goto :ERR2
goto :ALLOK
:ERR1
echo **** Warning: file1 did not work properly! ****
echo.
echo Press any key to terminate job ...
pause>nul
goto :END
:ERR2
echo **** Warning: file2 did not work properly! ****
echo.
echo Press any key to terminate job ...
pause>nul
goto :END
:ALLOK
echo ****** Job completed successfully *****
echo.
goto :END
:END
EXIT /B
I suppose, you only need CD to the workung directory in your case.
cd /d C:\01Game\1aedit\files\audio
start /wait C:\01Game\1aedit\1aedit.exe
Btw. I can't see a reason for start /wait, C:\01Game\1aedit\1aedit.exe should also work without it.

Resources