Batch Scripting: Command Not Running With If Statement - windows

So for starters, I'm kind of a scrub coder and I'm enjoying playing around with batch scripting.
I don't like to have multiple command line windows open, so I'm trying to script everything into this 1 batch file, including the ability to run standard command line commands.
Here's the section of my code that I'm having issues with.
:three
echo.
echo ***************************
echo **Enhanced Command Prompt**
echo ***************************
:three.b
echo.
set /p Return=Enter Command:
if '%Return%'=='Return' goto home
cmd /c %Return%
goto three.b
NOTE: I've also removed cmd /c, and %Return% excutes with no issue, but for the sake personal preference, I've kept the cmd /c present.
The issue with this line of text, is executing a command such as "Ping Google.com" crashes the window. So does ipconfig /all, and anything else that doesn't seem to execute right away.
If I remove the "IF=Return", then I have no problems running ping google.com or anything else, but I'm ultimately trapped in this section of code without that IF statement.
The IF statement itself functions, but "Ping X" and other commands do not without crashing the batch file.
Any help would be appreciated.
Thanks!

You will need to use double quotes in if as this is the proper way of quoting/comparing strings in batch file.
:three
echo.
echo ***************************
echo **Enhanced Command Prompt**
echo ***************************
:three.b
echo.
set /p Return=Enter Command:
if "%Return%" == "Return" goto home
cmd /c %Return%
goto three.b

Related

Running a batch file which requires inputs directly from folder

I have a batch file which requires 4 command line inputs. When I execute the batch file on the command prompt, it displays help message asking to input 4 values.
When I run this file directly from the folder, it opens cmd and closes immediately.
Is it possible to modify the batch file, so that when I run from folder it will open the cmd and then display the help message.?
Following is a mini version of my problem with 1 command input. The script is for a License file generation
#ECHO OFF
GOTO :continue
:continue
SETLOCAL
IF "%1" == "" GOTO :Help
::Set the Command Line Options
SET ARVERSION=%1
::Create Directory
SET OUT_PATH=%cd%
ECHO Initiating Generation...
if not exist %OUT_PATH% mkdir %OUT_PATH%
::Create License File - Calling 'Subs' will create the output with actual Version
Subs ARVERSION %ARVERSION% Input.txt 1>%OUT_PATH%\License.txt
ECHO Scripts are created # %OUT_PATH%
ECHO Generation Completed...
GOTO :End
:Help
ECHO Starting License File Generation...
ECHO Usage:
ECHO InstallerScriptGen.bat AR_VERSION
ECHO AR_VERSION - Version (3.2 or 4.0 or 4.2)
ECHO Example : InstallerScriptGen.bat 3.2.2
ECHO Please Note that input of incorrect values will result in wrong generation.
:End
ENDLOCAL
"Running directly from the folder" (by which I assume you mean "clicking on the icon from within Windows Explorer") causes Windows Explorer to execute the equivalent of CMD /C <<batchfilename>>. When invoked with /C, CMD exits (and the CMD window closes) as soon as the batch file ends. You can force the window to stay open long enough to read the output by ending the script with either the PAUSE command (which will cause it to wait for the user to press any key), or the TIMEOUT command (which will wait the indicated number of seconds before continuing, without a keypress). See SS64's help for the PAUSE and TIMEOUT commands for more information.

cmd.exe closes instantly when running batch file

I'm trying to make a simple batch file that will let me pick from a list of programs and run them based on my choice. For reference this is what I have so far:
#echo off
:menu
echo 1. zsnes
echo 2. Project64
echo 3. MAME
echo 4. PCSX2
echo 5. VBA
echo 6. DOSBox
set /p emu=Pick your emulator [1-6]:
if %emu%=1 goto zsnes
if %emu%=2 goto project64
if %emu%=3 goto mame
if %emu%=4 goto pcsx2
if %emu%=5 goto vba
if %emu%=6 goto dosbox
:zsnes
start /d "C:\Users\*username*\Documents\zsnes\" zsnesw.exe
I've just typed out through the zsnes program to test it. The command prompt launches and will ask for me to pick a choice. When I select 1, cmd.exe instantly closes but the program is not run. I made a script that contained only the start line and it worked fine. When I open cmd.exe manually and type that line in it also works fine. It just doesn't work in the context of my script. What could be causing this? Any advice would be greatly appreciated!
because your if is not correct .
Try with
if %emu% == 1 goto zsnes
or
if %emu% equ 1 goto zsnes
and so on.
Some syntax errors in IF and FOR commands leads force exist of the script.
probably you'll want also
:zsnes
start /d "C:\Users\*username*\Documents\zsnes\" zsnesw.exe
goto :eof
to avoid executuion of the code under the other labels.
write the following line at the end of the code or where you want to stop / pause your cmd.exe
timeout \t -1
this will pause your cmd screen and give you an option to close it by asking Yes/No ?.
Exactly like the one before me said, "if" should be:
if %emu% == 1 goto zsnes
Additionally, add "pause" after your batch, so you can read the error-messages when something fails.

Prevent batch file from closing after it executes an external .exe program

Believe it or not, I've searched all over stackoverflow and Google and can't find an answer to this that works for me.
(Windows 7 64-bit) I'm trying to create a batch file that runs multiple programs, one at a time. Simple, right? It works great until it runs the first .exe program. After the GUI of the .exe program closes, the batch file/cmd window also closes. I don't want it to close; I want the rest of the batch file to run.
Inside the batch file, I've tried the following methods, but none of them prevent the batch file from closing:
Git-1.9.5-preview20141217.exe
Git-1.9.5-preview20141217.exe
pause
call Git-1.9.5-preview20141217.exe
pause
start Git-1.9.5-preview20141217.exe
pause
start "" /wait Git-1.9.5-preview20141217.exe
pause
start "" /w Git-1.9.5-preview20141217.exe
pause
start "" /w /b Git-1.9.5-preview20141217.exe
pause
Does anyone know another method I can try? Maybe I should just call a powershell command or even translate the whole batch file to powershell, but I was trying to avoid powershell so that this script would work on multiple versions of Windows.
EDIT
I should also mention that with the methods above, the script closes before the pause command can be executed.
EDIT
Here's the full script with the rest of the .exe programs:
:Git
#echo off
(
echo.
echo.
echo DOWNLOADING GIT...
)
powershell -Command "(New-Object Net.WebClient).DownloadFile('http://github.com/msysgit/msysgit/releases/download/Git-1.9.5-preview20141217/Git-1.9.5-preview20141217.exe', 'Git-1.9.5-preview20141217.exe')"
(
echo.
echo.
echo LAUNCHING GIT INSTALLATION PROGRAM...
echo.
echo !IMPORTANT! WHEN YOU REACH THE SCREEN 'Adjusting your PATH environment',
echo SELECT 'Use Git from the Windows Command Prompt'.
echo KEEP ALL OTHER OPTIONS AT THE DEFAULT SETTING.
echo.
echo AFTER READING THE INSTRUCTIONS ABOVE, PRESS ANY KEY TO CONTINUE
)
pause
Git-1.9.5-preview20141217.exe
pause
GOTO CheckOS
:CheckOS
IF EXIST "%PROGRAMFILES(X86)%" (GOTO 64BIT) ELSE (GOTO 32BIT)
:32BIT
(
echo.
echo.
echo 32 BIT
echo.
echo DOWNLOADING TORTOISEHG (MERCURIAL)...
)
powershell -Command "(New-Object Net.WebClient).DownloadFile('http://bitbucket.org/tortoisehg/files/downloads/tortoisehg-3.2.4-x86.msi', 'tortoisehg-3.2.4-x86.msi')"
(
echo.
echo.
echo LAUNCHING TORTOISEHG INSTALLATION PROGRAM...
)
tortoisehg-3.2.4-x86.msi
GOTO MingW
:64BIT
(
echo.
echo.
echo 64 BIT
echo.
echo DOWNLOADING TORTOISEHG (MERCURIAL)...
)
powershell -Command "(New-Object Net.WebClient).DownloadFile('http://bitbucket.org/tortoisehg/files/downloads/tortoisehg-3.2.4-x64.msi', 'tortoisehg-3.2.4-x64.msi')"
(
echo.
echo.
echo LAUNCHING TORTOISEHG INSTALLATION PROGRAM...
)
tortoisehg-3.2.4-x64.msi
GOTO MingW
:MingW
(
echo.
echo.
echo DOWNLOADING MINGW...
)
powershell -Command "(New-Object Net.WebClient).DownloadFile('http://downloads.sourceforge.net/project/mingwbuilds/mingw-builds-install/mingw-builds-install.exe?r=http%3A%2F%2Fsourceforge.net%2Fprojects%2Fmingwbuilds%2F%3Fsource%3Dtyp_redirect&ts=1422376004&use_mirror=iweb', 'mingw-builds-install.exe')"
(
echo.
echo.
echo LAUNCHING MINGW INSTALLATION PROGRAM...
)
mingw-builds-install.exe
(
echo.
echo.
echo DONE! PRESS ANY KEY TO CLOSE.
)
pause
GOTO END
:END
For the lines that run the external .exe program, I've tried all 7 forms of the command that were listed at the beginning of this question, yet the script always closes before reaching the next pause command. I've also tried using cmd.exe /c and cmd.exe /k from the suggestions below, but unfortunately the script still quits before reaching the pause command.
EDIT
I figured out the problem (though not how to fix it). If I remove these lines:
GOTO CheckOS
:CheckOS
IF EXIST "%PROGRAMFILES(X86)%" (GOTO 64BIT) ELSE (GOTO 32BIT)
:32BIT
so that the following commands are under the same batch label, it works! But I'm not sure why including the :CheckOS label causes it to break. I've used this label in other batch scripts before, and they worked fine.
Nevermind, sorry. :S This only worked if the program had already been run. If it had already been run, a "modify, repair, or remove" screen popped up instead of an "install" screen. Apparently only the "install" screen closes the cmd.exe window.
FINAL EDIT
The parentheses were the problem. After removing them, everything else worked. Method number 1 at the beginning of this question works after removing the parentheses.
Try opening the executable in a new shell:
#echo off
cmd.exe /c Git-1.9.5-preview20141217.exe
echo Still here.
The /c switch tells the (new) shell to close when the program terminates. Execution of the batch script will be suspended until then.
For example:
#echo off
echo New window.
cmd.exe /c %WINDIR%\system32\notepad.exe
echo Window still open.
cmd.exe /c %WINDIR%\system32\notepad.exe
echo Window closed. You won't see this.

%ERRORLEVEL% is not working incase multiple commands on a Single line

I am trying the below commands and want to get exit of my process(%ERRORLEVEL%). But it is returning previous(last) executed exit code result of sample.exe. I want to get exit code of current command. My requirement is to execute multiple commands in single line*(not batch script)*.
Command:
cmd /c sample.bat "test" > c:\ouput.log & echo %ERRORLEVEL% > c:\returnCode.log
I even tried using "setlocal enableDelayedExpansion" like below. Still It is not returning the exit code of current command
cmd /c setlocal enableDelayedExpansion & sample.bat "test" > c:\ouput.log & echo %ERRORLEVEL% > c:\returnCode.log
Please let me know the way to get current command's exit code.
This should work:
cmd /V:ON /c sample.exe "test" > c:\ouput.log ^& echo !ERRORLEVEL! ^> c:\returnCode.log
/V:ON switch have the same effect of setlocal EnableDelayedExpansion. For further details, type: cmd /?
EDIT: Small error fixed, the & character must be escaped with ^, otherwise, the echo !ERRORLEVEL! command is not executed in the cmd /V:ON !!!
EDIT: Escaping the echo redirection via ^> causes just that echo to be piped into the log. If you do not escape that, the entire command is piped there, i.e. including the stdout stream from "sample.exe".
cmd /c sample.exe "test" > c:\ouput.log & call echo %%ERRORLEVEL%% > c:\returnCode.log
Should work for you. See endless SO items related to delayedexpansion
Thank for your response. I am able to get the exit code of current executed command with below command, only when I run through WMI class(Win32_Process). Using WMI client, I am executing the below command on Remote machine and it is working fine i.e. able to write exit code in Retrun.txt
Command:
cmd /V:ON /c sample.bat "test" > c:\Output.txt & echo !ERRORLEVEL! > c:\Return.txt
But if I run the same command in command prompt of the same remote machine, it is printing "!ERRORLVEL!" in Return.txt instead of "sample.bat" exit code.
I am curious to know why it is not working if I run from Command prompt of the same machine locally.

Batch file to determine if using Command Prompt

The last line in my batch file is pause. Is there any way to add a if condition to see if the script is run within command prompt or by double clicking to execute? I want to skip pause if it's running in command prompt.
...
...
if not RUN_IN_COMMAND_PROMPT (
pause
)
EDIT:
Hope to find a solution works in Windows Server 2003/2008, WinXP, Win7.
CALL :GETMYSWITCH %CMDCMDLINE%
IF /I "%MYSWITCH%" == "/C" ECHO I WAS STARTED IN THE EXPLORER & PAUSE
IF /I NOT "%MYSWITCH%" == "/C" ECHO I WAS STARTED IN A DOS SESSION
:GETMYSWITCH
SET MYSWITCH=%2
I know this is a year later but for future people searching you can use
If /I "%COMSPEC%" == %CMDCMDLINE% Goto SkipPause
pause
:SkipPause
It will skip the pause block if running from the command line and pause if running from batch file.
By definition, a shell script is always going to be run in a "command prompt". But try using the SESSIONNAME env var - it seems to NOT be present if the script was started by double-clicking instead of manually running it from a prompt.
Use the tty command.
Use the -s option and check the return value.

Resources