How to avoid creating an output file if no files are found?

I have a script package that requests a path, and also requests the type of files I want to look for in folders and subfolders in this path. Then it returns the path to these files in the output.txt file.

Here is 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 the output.txt file if the files are not found or IF the path entered is incorrect. Can someone please help me with this. Thank!

+4
source share
4 answers

If you use the FOR command to list files, it never redirects the output to a log file because the echo command will never be executed if the FOR command does not iterate the 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
+1

for %%# in ("%LOGFILE%") do (
   if %%~z# equ 0 (
       del /s /q "%LOGFILE%"
   )
)

. , 0 .

+2

for /F ExitCode 1, , :

(for /F "delims=" %%A in ('dir /b /s "%userInputPath%\*.%FileType%"') do echo %%A) > %LOGFILE% || rem
if errorlevel 1 del %LOGFILE%

, ...

, ExitCode for /F ; .

+2

, 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

, , FOR , DIR, STDERR .

, DIR, NUL, .

, , , , .

  • del /?
  • dir /?
  • echo /?
  • endlocal /?
  • for /?
  • set /?
  • setlocal /?

. Microsoft TechNet .

+1

Source: https://habr.com/ru/post/1667574/


All Articles