I want to run multiple commands in if condition in batch file.
I have tried below code but its not working for me.
IF not exist %directoryPath% (echo Invalid directory. goto :InvalidDirectory) ELSE (echo Sencha app build development started..)
Code:
:EnterDirectory
echo Enter your project directory
set /P directoryPath=
IF exist %directoryPath% (goto :init) ELSE (goto :InvalidDirectory)
:InvalidDirectory
echo This directory does not exists.
(goto :EnterDirectory)
:init
IF not exist %directoryPath% (goto :InvalidDirectory) ELSE (echo Sencha app build development started..)
When using batchfiles, don't try to do everything in one line. That makes your script unreadable and might even give you wrong/unexpected results, when you don't pay enough attention to the syntax (which easily happens). This kind of failures is hard to troubleshoot. Split it into several lines (ideally one command per line):
IF not exist %directoryPath% (
echo Invalid directory.
goto :InvalidDirectory
) ELSE (
echo Sencha app build development started..
)
If you insist on doing it in one line, & is the proper way to chain two commands:
IF not exist %directoryPath% (echo Invalid directory. & goto :InvalidDirectory) ELSE (echo Sencha app build development started..)
Related
Ok, I have batch file, just a simple one that hides and unhides folders.
I don't see why it cannot seem to execute accordingly;
Here is extended sample code:
#echo off
color a
title Folder/Drive hider Service
:jiki
echo Loading...
TIMEOUT /T 2 >nul
goto inputs
:inputs
echo Enabling security...
TIMEOUT /T 2 >nul
cls
goto menu
:menu
if EXIST "%~dp0\Encryption" (set status=Folder is locked.)
if EXIST "%~dp0\Logan_Documents" (set status=Folder is unlocked, to open it, enter open as your `action.)`
cls
echo.
echo STATUS: %status%
echo.
echo ----------------------------------------
echo FOLDER PROTECTOR by Logan
echo ----------------------------------------
echo.
echo Lock = Lock the folder(s)
echo Unlock = Unlock the folder(s)
echo Credits = For more info
echo V = Display your current version
echo Exit = Close the program
echo.
echo ----------------------------------------
echo For more info, just ask Logan!
echo ----------------------------------------
echo.
echo Select your action, %USERNAME%.
echo.
set /p "menu=>"
if /I %menu%== lock goto lock
if /I %menu%== unlock goto unlock
if /I %menu%== credits goto credits
if /I %menu%== v goto version
if /I %menu%== exit goto exit
goto invalid
and also a lot more, and every time I go to execute the script, it just leaves the status variable blank.
Here's what I've tried.
Reconfiguring all variables through a port, which then sorts based on if exist. doesn't work, just leaves status blank.
Using different variables. (Kinda stupid but I didn't want to think that I have all these errors because of a small typo.) Still left error blank.
Appreciate all efforts to resolve my problem and get this program working!
-Logan
if exist should work fine exactly as you use it. You don't strictly need the quotes, since the names don't include spaces. Also you don't need the parentheses since it is a single command.
But then again, it should work with them as well (I actually tested this), so the only thing I can imagine is that the files or folders are not found because the script is running in the wrong directory. After all you use just the names without any path, so the current directory should contain those files.
The 'current directory' isn't necessarily the directory in which the script is saved. If you are in 'C:\Foo' and you call 'C:\Bar\Script.bat', the current directory will still be 'C:\Foo'. The same goes for starting scripts through a shortcut.
To try this, you can use echo %CD% in your script to echo the current directory.
As a possible solution, you can use %~dp0 to use the actual directory in which the batch script is saved, so you always have a starting point to start from:
REM Check if 'Encryption' exists in the same folder as the batch file.
if EXIST "%~dp0\Encryption" (set status=Folder is locked.)
probably neither of the ifs are true, maybe because the active directory is not what you think it is. you can test this easily by inserting a set status=none above the ifs. or insert dir to see what the scrips actually sees at this point.
I am trying to write a .bat for the first time.
I am trying to install .msi using script, currently we are installing manually by double clicking on it.
Path from: d:/installed sw/$folder/.msi
Path to: D:/program files/app/
$folder means, it is different every time, as we are getting new msi to install which are provided in folder created by current date.
Here is the script I am trying:
#echo off
Title HOST: Installing Updates on %computername%
echo %computername%
set server=\\SERVERNAME or PATH\msifolder
:select
cls
echo Select one of the Following MSI Install Folders for installation task.
echo.
dir %server% /A:D /B
SET /P MSI=Please enter the MSI Folder to install:
SET source=%server%\%MSI%
echo Selected Installation %MSI%
echo.
echo.
:verify
ECHO Is This Correct?
echo.
echo.
ECHO 0: ABORT INSTALL
ECHO 1: YES
ECHO 2: NO,RE-SELECT
SET /p choice=Select YES, NO or ABORT? [0,1,2]:
if /i [%choice%]==[0] endlocal&goto end
if [%choice%]==[] goto BCurrentlocal
if [%choice%]==[1] goto yes
if [%choice%]==[2] goto no
endlocal
:no
goto select
:yes
set FILENAME=%MSI%
call %source%\%FILENAME%.msi
echo beginning %MSI% installation
pause
echo Exiting Install Script....
PING -n 4 127.0.0.1 >nul
exit
In line with set server I am adding the path to.
SET /P MSI is for path from.
However, it is not working.
Can anyone guide me what mistake I am doing?
This is how to install a normal MSI file silently:
msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log"
Quick explanation:
/L*V "C:\Temp\msilog.log"= verbose logging at indicated path
/QN = run completely silently
/i = run install sequence
The msiexec.exe command line is extensive with support for a variety of options. Here is another overview of the same command line interface. Here is an annotated versions (was broken, resurrected via way back machine).
It is also possible to make a batch file a lot shorter with constructs such as for loops as illustrated here for Windows Updates.
If there are check boxes that must be checked during the setup, you must find the appropriate PUBLIC PROPERTIES attached to the check box and set it at the command line like this:
msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log" STARTAPP=1 SHOWHELP=Yes
These properties are different in each MSI. You can find them via the verbose log file or by opening the MSI in Orca, or another appropriate tool. You must look either in the dialog control section or in the Property table for what the property name is. Try running the setup and create a verbose log file first and then search the log for messages ala "Setting property..." and then see what the property name is there. Then add this property with the value from the log file to the command line.
Also have a look at how to use transforms to customize the MSI beyond setting command line parameters: How to make better use of MSI files
Here is the batch file which should work for you:
#echo off
Title HOST: Installing updates on %computername%
echo %computername%
set Server=\\SERVERNAME or PATH\msifolder
:select
cls
echo Select one of the following MSI install folders for installation task.
echo.
dir "%Server%" /AD /ON /B
echo.
set /P "MSI=Please enter the MSI folder to install: "
set "Package=%Server%\%MSI%\%MSI%.msi"
if not exist "%Package%" (
echo.
echo The entered folder/MSI file does not exist ^(typing mistake^).
echo.
setlocal EnableDelayedExpansion
set /P "Retry=Try again [Y/N]: "
if /I "!Retry!"=="Y" endlocal & goto select
endlocal
goto :EOF
)
echo.
echo Selected installation: %MSI%
echo.
echo.
:verify
echo Is This Correct?
echo.
echo.
echo 0: ABORT INSTALL
echo 1: YES
echo 2: NO, RE-SELECT
echo.
set /p "choice=Select YES, NO or ABORT? [0,1,2]: "
if [%choice%]==[0] goto :EOF
if [%choice%]==[1] goto yes
goto select
:yes
echo.
echo Running %MSI% installation ...
start "Install MSI" /wait "%SystemRoot%\system32\msiexec.exe" /i /quiet "%Package%"
The characters listed on last page output on entering in a command prompt window either help cmd or cmd /? have special meanings in batch files. Here are used parentheses and square brackets also in strings where those characters should be interpreted literally. Therefore it is necessary to either enclose the string in double quotes or escape those characters with character ^ as it can be seen in code above, otherwise command line interpreter exits batch execution because of a syntax error.
And it is not possible to call a file with extension MSI. A *.msi file is not an executable. On double clicking on a MSI file, Windows looks in registry which application is associated with this file extension for opening action. And the application to use is msiexec with the command line option /i to install the application inside MSI package.
Run msiexec.exe /? to get in a GUI window the available options or look at Msiexec (command-line options).
I have added already /quiet additionally to required option /i for a silent installation.
In batch code above command start is used with option /wait to start Windows application msiexec.exe and hold execution of batch file until installation finished (or aborted).
Although it might look out of topic nobody bothered to check the ERRORLEVEL. When I used your suggestions I tried to check for errors straight after the MSI installation. I made it fail on purpose and noticed that on the command line all works beautifully whilst in a batch file msiexec dosn't seem to set errors. Tried different things there like
Using start /wait
Using !ERRORLEVEL! variable instead of %ERRORLEVEL%
Using SetLocal EnableDelayedExpansion
Nothing works and what mostly annoys me it's the fact that it works in the command line.
Have a weird issue, firstly am using batch files to install applications..the installations are working fine without any issue.
I have at the end of the batch if the error level is NEQ 0 output the error code to a file, but the output is always 9009.
From searching the web for 9009 it says that the executable cannot be found, but surely it can as the application installs fine.
Here is a sample of one of my batch scripts to install:
IF exist %windir%\LogFolder\BoxSync4.0x86.txt ( goto eof ) ELSE ( goto BoxSyncInstall )
:BoxSyncInstall
msiexec /i "\\servername\InstallFolder\BoxSync\SyncMSI32.msi" /qn
if %ErrorLevel% EQU 0 (
>>"\\servername\gpolog\BoxSync4.0x86.csv" echo "%computername%","%date%","%Time%","%ErrorLevel%","Box Sync 4.0 x86 Installed"
>>"%windir%\gpologs\BoxSync4.0x86.txt" echo "Box Sync 4.0 x86 Installed"
)
else if %ErrorLevel% NEQ 0(
>>"\\servername\gpolog\BoxSyncErrorsx86.csv" echo "%computername%","%date%","%Time%","%ErrorLevel%","Error trying to install/upgrade to BoxSync4.0x86"
)
:eof
Does anyone have any ideas why I might be getting this error constantly?
Thanks
Mikoyan
Try using setlocal enabledelayedexpansion at the start of your batch file, and !ERRORLEVEL! inside your IF.
See also:
ERRORLEVEL inside IF
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/setlocal.mspx?mfr=true
http://batcheero.blogspot.ru/2007/06/how-to-enabledelayedexpansion.html
The problem is syntax, you need a space between your 0 and (, like so:
IF exist %windir%\LogFolder\BoxSync4.0x86.txt ( goto eof ) ELSE ( goto BoxSyncInstall )
:BoxSyncInstall
msiexec /i "\\servername\InstallFolder\BoxSync\SyncMSI32.msi" /qn
if %ErrorLevel% EQU 0 (
>>"\\servername\gpolog\BoxSync4.0x86.csv" echo "%computername%","%date%","%Time%","%ErrorLevel%","Box Sync 4.0 x86 Installed"
>>"%windir%\gpologs\BoxSync4.0x86.txt" echo "Box Sync 4.0 x86 Installed"
)
else if %ErrorLevel% NEQ 0 (
>>"\\servername\gpolog\BoxSyncErrorsx86.csv" echo "%computername%","%date%","%Time%","%ErrorLevel%","Error trying to install/upgrade to BoxSync4.0x86"
)
:eof
EDIT: If the installer needs admin privileges and this is a Win8+ OS, you might have security restrictions, in that case, copy the msi installer into the %TEMP% folder and run it from there. The reason this happens is because when you run the command prompt in Administrator mode, it restricts use of unc paths (for "security" reasons).
Try also pushd and popd as #dbenham keeps reminding us: LINK
found where the issue lied it is under the ELSE IF as I watched the install script run by not being silent.
After removing ELSE the script ran fine. Thanks again for your help as you have guided me with other tricks.
I am trying to write a batch file that will write a new line with a "MOVE" command to a second batch file. We have a master batch file with a MOVE command for every PC that uses a piece of our software so we can back the records up to a network drive (scheduled to run daily). Data on the local PC's gets deleted after 20 days and we need to create a place to hold these files permanently. Unfortunately this is the best way to keep our data backed up, I'm just trying to automate the process to make the process as easy as I can for my department. I'm trying the command below but I think it's an issue with the quotation marks. Any help would be appreciated, thanks!
:START
ECHO.
SET /p pcid=Please enter the PCID that you would like to setup for Auto-Archiving:
IF "%pcid%"=="%%" (GOTO CONFIRMPC)
IF "%pcid%"=="exit" (GOTO END)
:CONFIRMPC
ECHO.
ECHO Please verify that "%pcid%" is correct...
ECHO.
SET /p verify=Enter y/n...
IF "%verify%"=="y" (GOTO SETUPAUTOARC)
IF "%verify%"=="n" (GOTO START)
IF "%verify%"=="%%" (GOTO VERIFYERROR)
IF "%verify%"=="exit" (GOTO END)
:VERIFYERROR
ECHO.
ECHO Please enter a valid (y/n) response...
(GOTO CONFIRMPC)
:SETUPAUTOARC
ECHO.
ECHO Creating directory...
MKDIR "\\server32\e$\Backup Data\%pcid%"
ECHO.
(HERE IS WHERE I'M RUNNING INTO TROUBLE)
ECHO "MOVE "\\%pcid%\C$\Program Files\Application\Data\*.xml" > "\\server32\c$\scripts\masterbackup.bat
ECHO.
SET /p endresp=Finished! Would you like to run another PCID? (y/n)
IF "%endresp%"=="y" (GOTO START)
IF "%endresp%"=="n" (GOTO END)
:END
exit
ECHO "MOVE "\\%pcid%\C$\Program Files\Application\Data\*.xml" > "\\server32\c$\scripts\masterbackup.bat
---- ^ Remove this quote and add an extra waaaaay up at the very end...................................^.here
The syntax is ECHO string > file
Where quotes should be balanced and need to be placed around any (full-)filename that contains spaces (etc.)
Note also that > will write the data to a NEW file, deleting the exiting (if any). Use >> to APPEND to an existing file.
Having said that, all the command would do is put or add a line
MOVE "\\%pcid%\C$\Program Files\Application\Data\*.xml"
to the file "\\server32\c$\scripts\masterbackup.bat"
That doesn't seem to be particularly rational. Shouldn't you be MOVEing the fileset to somewhere and appending that move command to the batch?
Why is batch not running this second for loop? What am i doing wrong? The first loop runs fine, but the second loop is never hit. I even put an echo statement after the first loop and it is not even displayed.
FOR /D %%X in (..\Apps\Mine\*) do if exist "%%X\AndroidManifest.xml" ("%1\android.bat" update project -p "%%X") else (
echo This is not an android project.
)
FOR /D %%Y in (..\Apps\Theirs\*) do if exist "%%Y\AndroidManifest.xml" ("%1\android.bat" update project -p "%%Y") else (
echo This is not an android project.
)
More details
The current working directory also has no () or spaces in the name.
Windows7 64bit.
This is the exact argument i am using:
> update_project.bat C:\Users\MyUserName\android-sdks\tools
That is all the contents of the batch script. There is nothing else in it.
Here is the directory structure. The batch script is run from the CWD.
Projects
Apps
Mine
App1
App2
Theirs
App3
App4
Tools (CWD)
Add a CALL statement in front of "%1\android.bat". If you don't use CALL, control will not be returned from "%1\android.bat".
Like this,
FOR /D %%X in (..\Apps\Mine\*) do if exist "%%X\AndroidManifest.xml" (CALL "%1\android.bat" update project -p "%%X") else (
echo This is not an android project.
)
FOR /D %%Y in (..\Apps\Theirs\*) do if exist "%%Y\AndroidManifest.xml" (CALL "%1\android.bat" update project -p "%%Y") else (
echo This is not an android project.
)