Conditional IF EXIST Statement for multiple filenames in BATCH file - batch-file

I'm working on the following batch script and I'm not sure how I can achieve the results I'm looking for. I searched here as well as online, but I didn't see anything that looked like what I'm looking for. Any help is appreciated.
I need to check if two files exist as well as if they don't. Currently I've got the code below working, however if one file exists or is missing it goes in a 3rd direction (I've updated the code to account for the 3rd direction so now it works fine, but I know there is much room for improvement!). I know it's not pretty, but it works and the pretty code doesn't.
Please note that there are other files in the same directory with the same extensions, so searching by extension will not work.
Working Code:
#echo off
echo checking file structure...
if exist "file1.exe" (
if exist "file2.zip" (
goto ok
)
)
if not exist "file1.exe" (
if not exist "file2.zip" (
goto download
)
)
if not exist "file1.exe" (
goto download
)
)
if not exist "file2.zip" (
goto download
)
)
:download
echo downloading missing files.
:ok
echo Install successful
What I would like to do:
(The following code isn't expected to work, it's my thoughts written out)
#echo off
set file1=setup.exe
set file2=package.zip
if exist $file1 && $file2 then goto ok
else if not exist $file1 || $file2 goto download
Example of why checking for the two files alone will not work
echo checking file structure...
if exist "setup.exe" if exist "package.zip" goto TEST1
if not exist "setup.exe" if not exist "package.zip" goto TEST2
ECHO [Error!] - 1 File is present, the other is missing!
PAUSE
:TEST1
ECHO [Success!] - Found both files, YAY!
PAUSE
:TEST2
ECHO [Error!] - No matching files found.
PAUSE

The parentheses are neccessary for the else clause.
#echo off
echo checking file structure...
if exist "file1.exe" (
if exist "file2.zip" (
goto :ok
) else goto :download
) else goto :download
:download
echo downloading missing files.
:ok
echo Install successful
But the else isn't required at all because the program flow falls through to the download label
#echo off
echo checking file structure...
if exist "file1.exe" if exist "file2.zip" goto :ok
:download
echo downloading missing files.
:ok
echo Install successful

Why perenthesize? Simply try.
#echo off
echo checking file structure...
if exist "file1.exe" if exist "file2.zip" echo Install successful
if not exist "file1.exe" echo downloading missing "file1.exe"
if not exist "file2.zip" echo downloading missing "file2.zip"
or in a loop:
#echo off
for %%i in ("file1.exe" "file2.zip") do if not exist "%%i" echo %%i Must be downloaded & goto :EOF
echo Successful Installation

:again
for %%a in ("file1.exe" "file2.zip") do if not exist "%%~a" call :download "%%~a" &goto again
And then write an internal procedure to download the missing file supplied as %1
Possibly you'd want to install a counter and report in the :download procedure if the download is being executed, and if so of which file - and count the number of iterations to stop the process if the download fails too often.
An advantage here is that there's no real limit to the number of filenames that can be included in the parentheses

Found the solution! Added some if exist parameters to account for empty folders.
for /D %%I in ("%~dp0*") do (
cd /D %%I
if exist *pm.wav (
if exist *.xml (
tar -cvzf %%~nxI.tar.gz *pm.wav *.xml
)
)
)
cd..

Download & execute
#echo off
echo checking file structure...
if exist "C:\Users\Himel\Desktop\5MB.zip" (
if exist "C:\Users\Himel\Desktop\5MB.zip" (
goto ok
)
)
if not exist "C:\Users\Himel\Desktop\5MB.zip" (
if not exist "C:\Users\Himel\Desktop\5MB.zip" (
goto download
)
)
if not exist "C:\Users\Himel\Desktop\5MB.zip" (
goto download
)
)
if not exist "C:\Users\Himel\Desktop\5MB.zip" (
goto download
)
)
:download
echo downloading missing files.
SETLOCAL
rem FOR DOWNLOADING FILES, THIS SCRIPT IS USING THE "BITSADMIN.EXE" SYSTEM FILE.
rem IT IS PRESENT ON MOST WINDOWS VERSION, PROBABLY FROM WINDOWS XP TO WINDOWS 10.
:SETUP
rem URL (5MB TEST FILE):
SET "FILE_URL=http://ipv4.download.thinkbroadband.com/5MB.zip"
rem SAVE IN CUSTOM LOCATION:
rem SET "SAVING_TO=C:\Folder\5MB.zip"
rem SAVE IN THE CURRENT DIRECTORY
SET "SAVING_TO=5MB.zip"
SET "SAVING_TO=%~dp0%SAVING_TO%"
:MAIN
ECHO.
ECHO DOWNLOAD SCRIPT EXAMPLE
ECHO.
ECHO FILE URL: "%FILE_URL%"
ECHO SAVING TO: "%SAVING_TO%"
ECHO.
rem UNCOMENT AND MODIFY THE NEXT LINE IF YOU NEED TO USE A PROXY SERVER:
rem CALL :DOWNLOAD_PROXY_ON "PROXY-SERVER.COM:8080"
rem THE MAIN DOWNLOAD COMMAND:
CALL :DOWNLOAD_FILE "%FILE_URL%" "%SAVING_TO%"
rem UNCOMMENT NEXT LINE FOR DISABLING THE PROXY (IF YOU USED IT):
rem CALL :DOWNLOAD_PROXY_OFF
:RESULT
ECHO.
IF EXIST "%SAVING_TO%" ECHO YOUR FILE HAS BEEN SUCCESSFULLY DOWNLOADED.
IF NOT EXIST "%SAVING_TO%" ECHO ERROR, YOUR FILE COULDN'T BE DOWNLOADED.
ECHO.
:EXIT_SCRIPT
PAUSE
EXIT /B
rem FUNCTIONS SECTION
:DOWNLOAD_FILE
rem BITSADMIN COMMAND FOR DOWNLOADING FILES:
bitsadmin /transfer mydownloadjob /download /priority FOREGROUND %1 %2
GOTO :EOF
:DOWNLOAD_PROXY_ON
rem FUNCTION FOR USING A PROXY SERVER:
bitsadmin /setproxysettings mydownloadjob OVERRIDE %1 "<local>"
GOTO :EOF
:DOWNLOAD_PROXY_OFF
rem FUNCTION FOR STOP USING A PROXY SERVER:
bitsadmin /setproxysettings mydownloadjob NO_PROXY
GOTO :EOF
share
:ok
echo Install successful

Related

how to script MKDIR and install .bat

nerds and pro´s.
I am trying to get my head around a simple thing like this:
#echo off
MKDIR "C:\Program Files (x86)\Start-proTM" (
IF %ERRORLEVEL0%(
GOTO :ok
)
IF %ERRORLEVEL1%(
GOTO :no
)
)
IF EXIST "C:\Program Files (x86)\Start-proTM" (
GOTO :ok
) ELSE (
MKDIR "C:\Program Files (x86)\Start-proTM"
)
IF %ERRORLEVEL%=0 (
GOTO :ok
)
IF %ERRORLEVEL%=1 (
GOTO :no
)
#ECHO off
:ok
ECHO Ok...
pause
:no
ECHO NO...
Pause
don´t mind the rand. PAUSE,
just to simplyfy things.
:ok REM would be rewritten to take care of the install process.
:no REM is the %ERRORLEVEL% return in txt for the user.
Just want a simple .exe to MKDIR, check if such has been created. Then install(extract) the files in set directory. And let the user know the current status of the install process, through promt in cmd.exe
Anyone? any suggestions?
I might be totally blinded, by the simplicity of the structure?
This is how I've done something like this before:
set "TARGETPATH=C:\Program Files (x86)\Start-proTM"
echo Extracting files to %TARGETPATH%
if exist "%TARGETPATH%" (rmdir "%TARGETPATH%" /S /Q || exit /b 1)
mkdir "%TARGETPATH%" || exit /b 1
Note: If you try to set and use variables inside a parenthetical scope, you will need to do setlocal EnableDelayedExpansion and surround the variable names with exclamation (!) points instead of percent (%) signs.

Windows batch file to find files in a folder for error checking

This part of my script is supposed to go through directories looking for *.wim files and if it finds them on the "images" folder, proceed. However, it is going straight to the "else" part of the code :/
ECHO. Checking for WIMs
ECHO ............................................
ECHO.
for /F "tokens=*" %%f in ('dir /B /S "%w%:\data\images"') do (
if exist "%%~ff\*.wim" (
ECHO found me some wims! let's continue.
GOTO actionmenu
) else (
ECHO This script requires a wim repository folder to proceed. make sure you have
ECHO properly populated the "\Images" folder before re-running this script
goto end
)
)
You don't even need a for loop. Dir gives an %errorlevel% of 1, if it doesn't find something:
dir /B /S "%w%:\data\images\*.wim" >nul && (
echo found at least one wim file.
) || (
echo no wim files found.
)
&& works as "if previous command was successful (dir found at least one file), then"
|| is the opposite: " if previous command failed (dir didn't find a matching file) then"
for /F "tokens=*" %%f in ('dir /B /S /AD "%w%:\data\images"') do (
if exist "%%f\*.wim" (
ECHO found me some wims! let's continue.
GOTO actionmenu
) else (
ECHO This script requires a wim repository folder to proceed. make sure you have
ECHO properly populated the "\Images" folder before re-running this script
goto end
)
)

batch works on Windows 7 on WinCE sucks

I have written the following synchronization code batch to flush all data inside a master hard drive into a backup drive. Because of drives name can change I used a trick putting master.txt into source drive and backup.txt into backup drive. In this way I can easily find source and backup. Omn windows 7 it works pretty well but once inside WinCE the hell.
cls
::#echo off
PATH=\hard disk;\hard disk2;\hard disk3;\hard disk4;e:;f:;g:
for %%A in ("%path:;=";"%") do (
if exist %%~A\master.txt (
echo found %%~A\master.txt
SET data=%%~A\Rilevamenti
)
if exist %%~A\backup.txt (
echo found %%~A\backup.txt
SET backup=%%~A
)
)
echo source path is: %data%
:logfile
Time /T > Time.dat
SET /P ftime= < Time.dat
SET DirName=BackupFiles%date:~6%%date:~3,2%%date:~0,2%%ftime:~0,2%%ftime:~3,2%
SET backup=%backup%\%DirName%
echo backup dir is: %backup%
pause
mkdir "%backup%"
echo 1 > LogSyncFile_src
echo 1 > LogSyncFile_dst
SET COPYCMD=/Y
for /R "%data%" %%F in (*.CSV) do (
move %%F %backup%\%%~nxF
echo %%~nxF >> LogSyncFile_src
)
for /R "%backup%" %%F in (*.CSV) do (
echo %%~nxF >> LogSyncFile_dst
)
SET /P Build=<LogSyncFile_src
SET /P Synch=<LogSyncFile_dst
if %Build%==%Synch% (
goto :delete
) else (
goto :fail
)
:fail
echo synchronization failed!
goto :exit
:lowmemory
echo Insufficient memory to copy files or
echo invalid drive or command-line syntax.
goto :exit
:abort
echo You pressed CTRL+C to end the copy operation.
goto :exit
:delete
echo synchronization completed!
goto :exit
:exit
pause
On WinCE for the first loop I get:
for %%A in ("%path:;=";"%") do ( Cannot execute for.exe
Any help on what's going on? It is the second time I write the same batch in a different way to get working on WinCE as well but it seems I am missing something...

Append String to file name in dos Syntax Error Need

#ECHO off
title Rename Script
set dir1=%1
set STR=%2
set count=1
:Start
cls
echo 1. Rename Files
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto rename
if %choice%==2 exit
:rename
cls
echo Running Rename Script for STR=%STR%
FOR %%n in (%dir1% *.*) DO (
ren %%n %STR%%%n
echo %STR%%%n)
echo done
pause
C:>yogesh>LDK.bat C:\yogesh app
OUTPUT:
Running Rename Script for STR=app
The syntax of the command is incorrect.
appC:\yogesh
appa3dapi.dll
appHLTV-Readme.txt
apphltv.cfg
appkver.kp
applanguage.inf
appLDR.bat
appMp3dec.asi
appMss32.dll
appMssv12.asi
appMssv29.asi
appTrackerNET.dll
The batch file cannot be found.
C:\yogesh>
There are few issues with this script:
" The syntax of the command is incorrect." I do not know where is the problem in script.
How to get the count of number of files renamed ?
Files get renamed into the directory where the .bat file resides I want to rename the files in specified folder as argument in variable dir1
Please let me know if you need more information.
Here is a solution without using CD. You needed to put a \ between your dir1 variable and *.* instead of a space. You needed quotes to protect against spaces in names. Use FOR variable modifiers ~nx to get just the name and extension (removes any drive and path info). Finally, use SET /A to perform math.
#ECHO off
title Rename Script
set "dir1=%~1"
set "STR=%~2"
set count=1
:Start
cls
echo 1. Rename Files
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto rename
if %choice%==2 exit
:rename
cls
echo Running Rename Script for STR=%STR%
set cnt=0
FOR %%F in ("%dir1%\*.*") DO (
ren "%%F" "%STR%%%~nxF"
echo %STR%%%~nxF
set /a cnt+=1
)
echo %cnt% files were renamed.
echo done
pause
Here you go:
#ECHO off
title Rename Script
set /A count=1
:Start
cls
echo 1. Rename Files
echo 2. Quit
set /p choice=I choose (1,2):
if %choice%==1 goto rename
if %choice%==2 exit
:rename
cls
set /p STR=choose a start-string:
echo Running Rename Script for STR=%STR%
FOR %%n in (*.*) DO (
ren "%%n" "%STR%%%n"
echo "%STR%%%n"
set /A count+=1)
echo count %count%
echo done
pause
we can save the current path in OLDDIR and then change the path to the one the user gave, at the end of the script we'll go back to OLDDIR using CD
you need to set the counter with /A
UPDATE for dbenham:
A small proof :)) that it worked (for me) with filenames that contains spaces:

CMD: file extensions recognition?

I want to have my batch file to recognise the extension of the file the user types in in the following situation:
The user has to type in a folder OR a .zip/.rar file.
if its a folder, it should use GOTO :folder
if its a .zip/.rar, it should use GOTO :ziprar
(if it is possible without 3rd party software, than dont going to say about it please)
You can extract substrings from environment variables, which you can use to get the file extension:
set FILENAME=C:\mypath\myfile.rar
if "%FILENAME:~-4%"==".rar" (
echo It is a RAR file!
) else (
echo Not a RAR file
)
If the user can specify the path as a parameter to the batch file, that is the best option since "%~1" is less problematic than "%filename%" like I said in a comment to Helen's answer. It would look something like:
setlocal ENABLEEXTENSIONS
FOR %%A IN ("%~1") DO (
IF /I "%%~xA"==".rar" goto ziprar
IF /I "%%~xA"==".zip" goto ziprar
)
goto folder
If you can't use a parameter, the best I could come up with is:
setlocal ENABLEEXTENSIONS
REM set file="f~p 'o%OS%!OS!^o%%o.rar"
set /p file=Enter a folder path or a zip/rar file name:
FOR /F "tokens=*" %%A IN ("%file%") DO (
IF /I "%%~xA"==".rar" goto ziprar
IF /I "%%~xA"==".zip" goto ziprar
)
goto folder
There is a possibility that there is a valid filename that causes syntax errors, but I did not find one during my limited testing.
You might also want to consider a basic folder check rather than checking file extensions:
IF EXIST "%~1\*" (goto folder) ELSE goto ziprar

Resources