Below is a batch file which accepts 2 or more arguments. The
- first argument shall be a base directory to search for files (for example D:\temp)
- second argument and consecutive shall be file name pattern to search (for example 2017_02_01 or myapp)
The batch file will do the following
- Check if first argument is empty and display appropriate message.
- Check if first argument is not existing directory or display appropriate message.
- Call a subroutine to parse and take action on each and every argument.
- In the subroutine check if any unwanted symbols are in arguments and display appropriate message.
- In the subroutine do not take action on first argument.
- In the subroutine check if the file pattern argument exists in base directory which is first argument. Here the check is failing and always returns 1 which is incorrect.
- If the file pattern argument exists then take action like add the file to a temporary zip file using 7zip. Similarly do for rest of the arguments.
- If the argument is empty then stop subroutine.
Below is the batch file.
@echo off
set BASE_DIR=%1
REM check if first argument is empty and display appropriate message
set NEW_DIR=%BASE_DIR%X
if %NEW_DIR%==X goto displayUsage
REM check if first argument is not existing directory or display appropriate message
if not exist %BASE_DIR% goto displayUsage
cd /d C:\temp\
if exist "C:\temp\temp.zip" del /q /f "C:\temp\temp.zip"
call :subr %*
exit /b
:subr
rem check if any unwatned symbols are in arguments
if exist "C:\temp\temp.txt" del /q /f "C:\temp\temp.txt"
echo %* > "C:\temp\temp.txt"
findstr /r ".*[<>/|?*%%].*" "C:\temp\temp.txt" >nul
if %errorlevel% equ 0 goto displayUsage
rem start parsing each argument
for %%A in (%*) do (
if not %%A==%BASE_DIR% (
rem check if file exists and take action on it
pushd %BASE_DIR%
dir /b /s /a-d *%%A* | find "File not found"
set FILE_EXISTS=%errorlevel%
rem HERE FILE_EXISTS STATUS IS ALWAYS 1 IRRESPECTIVE OF FILE PRESENCE
popd
if %FILE_EXISTS% equ 0 (
rem take action on the file like add it to a zip file
"7za.exe" a -r -y "C:\temp\temp.zip" %BASE_DIR%\*%%A*.*
) else (
echo File %%A does not exists in %BASE_DIR%
)
) else (
echo No need to parse base directory %%A
)
)
exit /b
:displayUsage
echo Usage: create-logs-zip.bat existing-base-directory log-file-name
echo Do not use symbols: ^< ^> / ? ^| ^*
goto end
:end
if exist "C:\temp\temp.zip" del /q /f "C:\temp\temp.zip"
if exist "C:\temp\temp.txt" del /q /f "C:\temp\temp.txt"
exit /b
Can any one point what is the mistake in checking file exists and share why it is always returning 1.
Request: Please do not give power shell or cmdlets or VB script as alternatives.