Kelvyn
Kelvyn

Reputation: 11

Windows Batch script to find files with specific extensions, write their directories to a text file

First off, I'm new to batch files.

Basically I'm creating a backup program that finds certain directories based on what files they contain. It saves this list so it doesn't have to search again on the next run.

I don't have access to a windows rig until later in the week, so this code is untested/psudocode.

for /R "c:\my\dir" %%f in (*.pdf | *.doc) do (
    set "folderPath=%%f"
    echo %folderPath%>> directoryList.txt
)

load %readPath% from directoryList.txt   ::Not sure how to read lines one by one?
if %readPath% != eof (
    xcopy %folderPath% %writePath% /e/v/c/y/h/r/d >> %logFile%
)

Upvotes: 1

Views: 15547

Answers (1)

JosefZ
JosefZ

Reputation: 30093

Next script might become a starting point for you. Explanation in code via rem comments.

@ECHO OFF >NUL
    rem set up output directory
set "writePath=c:\my\writedir"

    rem create empty file
type nul>directoryList.txt

    rem get a list of unique folder names
    rem might contain recursion in names, e.g.
    rem c:\my\dir\foo 
    rem c:\my\dir\foo\subfoo 
for /F "tokens=*" %%f in ('dir /B /A:D /S "c:\my\dir\*.*"') do (
    if exist "%%~ff\*.doc" ( 
        echo "%%~ff">> directoryList.txt
    ) else (
        if exist "%%~ff\*.pdf" echo "%%~ff">> directoryList.txt
    )
)
    rem treat the list of unique names
    rem check the list, compare to output 
for /F "tokens=*" %%f in ('type directoryList.txt') do (
        rem check next line otput carefully before removing echo
    echo xcopy "%%~f" "%writePath%" /e/v/c/y/h/r/d
        rem ? or with trailing backslashes "%%~f\"  "%writePath%\"
        rem ? or with trailing \ escaped   "%%~f^\" "%writePath%^\"
        rem not tested: XCOPY logic, paths, switches
        rem not tested: recursion in input file
)

Resouces:

Upvotes: 2

Related Questions