Reputation: 49
I have a batch script that asks for a path and also asks for the type of files I want to search in the folders and subfolders in that path. Then it returns the path to those files in an output.txt file.
Here's my code:
@echo on
set LOGFILE=output.txt
set /P userInputPath=Enter the path you'd like to search?
set /p "FileType=Enter file type(s) here (ex: txt, pdf, docx): "
call :LOG > %LOGFILE%
exit
:LOG
for %%A in (%FileType%) do (dir /b /s %userInputPath%\*.%%A)
@pause
I want to avoid creating an output.txt file IF no files are found or IF the path entered is wrong. Can anyone please help me with this. Thank you!
Upvotes: 4
Views: 212
Reputation: 49186
One more solution to find also files with hidden file attribute set which are ignored by command FOR:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
set "LOGFILE=output.txt"
set /P "userInputPath=Enter the path you'd like to search: "
set /P "FileType=Enter file type(s) here (ex: txt, pdf, docx): "
del "%LOGFILE%" 2>nul
for %%A in (%FileType%) do (
for /F "delims=" %%B in ('dir /A-D /B /S "%userInputPath%\*.%%A" 2^>nul') do (
>>"%LOGFILE%" echo %%B
)
)
endlocal
This solution is slower as the other ones as the inner FOR reads all lines output by command DIR which are next output to handle STDERR redirected to the log file.
The error message(s) output by command DIR are redirected to device NUL to suppress them.
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
del /?
dir /?
echo /?
endlocal /?
for /?
set /?
setlocal /?
See also the Microsoft TechNet article Using command redirection operators.
Upvotes: 1
Reputation: 14320
If you use a FOR command to list the files it will never redirect output to the log file because the echo command will never execute if the FOR command does not iterate any file names.
@echo off
set "LOGFILE=output.txt"
del "%logfile%"
:LOOP
set /P "userInputPath=Enter the path you'd like to search;"
set /p "FileType=Enter file type(s) here (ex: txt, pdf, docx):"
IF NOT EXIST "%userInputPath%" (
echo %userInputPath% does not exist
GOTO LOOP
)
for /R "%userInputPath%" %%G in (%FileType%) do echo %%G>>%LOGFILE%
pause
Upvotes: 1
Reputation: 67256
You may use the ability of for /F
command of return an ExitCode of 1 when no data was processed, that is:
(for /F "delims=" %%A in ('dir /b /s "%userInputPath%\*.%FileType%"') do echo %%A) > %LOGFILE% || rem
if errorlevel 1 del %LOGFILE%
Note that this code is used instead of the subroutine call...
You may read a detailed explanation of how the ExitCode value is used in for /F
command at this question; look for Exit Code management.
Upvotes: 2
Reputation: 57322
you can add
for %%# in ("%LOGFILE%") do (
if %%~z# equ 0 (
del /s /q "%LOGFILE%"
)
)
at the end.It checks if the size of the log file is 0 and if yes deletes it.
Upvotes: 2