I've been pulling pieces of script from around the internet, building something to search all folders under one parent folder, finding certain files and copying them to a new location. (We have a directory with endless empty and occupied folders, and are trying to find a handful of files without manually searching)
So far, the script works, but only if the named files (from the Names.txt doc) are directly under the parent folder (...\source). If they're inside any of the folders within the parent folder (...\source\folder1\folder2\etc), they are not searched and nothing turns out. What am I missing?
@echo off
pushd C:\Users\username\Desktop\TestBatches
set /p SourceFolder=Enter the path of source folder and press 'Enter':
cls
for /f "tokens=* delims=" %%a in ('type Names.txt') do xcopy /hrkvy "%SourceFolder%\%%a" ".\destination"
popd
pause
Do I put a wildcard in the command prompt, when typing in the source path? Or, do I put something into the batch that will automatically do this?
I'm a bit lost. Thank you for the help!
Answer
I am going to take you straight to some advanced batch concepts here.
In the following example, I am using batch functions to accomplish this task. This is not the most efficient way to reach the goal but it will show you the kinds of things you CAN do. I am very tired still so this solution might be a silly one (but it works)
Even if you don't go this route, perhaps "dir /s /b FILEMASK" was what you were looking for.
@echo off
:: This assumes that this batch is in the same folder as Names.txt and the .\destination folder
:: This batch DOES NOT check things it should like the existence of %SourceFolder% or if .\destination even exists
Set ThisDir=%~DP0
Set DestinationDir=%ThisDir%\destination
Set NamesFile=%ThisDir%\Names.txt
Set /p SourceFolder=Enter the path of source folder and press [Enter]:
for /f "delims=" %%a in ('type %NamesFile%') do call :SearchName "%%a"
pause
goto :EOF
:: ----------------------------------------------------------------
:SearchName
pushd %SourceFolder%
for /f "delims=" %%f in ('dir /s /b %1') do call :FoundFile "%%f"
popd
goto :EOF
:: ----------------------------------------------------------------
:FoundFile
xcopy /hrkvy "%1" "%DestinationDir%"
goto :EOF
The first for loop does nothing but call a function :SearchName for each of the names in your text file.
The :SearchName function switches to the directory specified by "Set /p" and does a "dir /s /b NAME_PASSED_FROM_TEXT_FILE". It pumps lines it gets (files it found) to a :FoundFile function.
The :FoundFile function copies the file passed to it.
No comments:
Post a Comment