Batch: Copy, then delete, files from list; need error handling

I've looked through the many batch-from-a-list topics on here, but haven't found anything on point. I have a text file with a list of files, including paths. I need to first copy these files out to an external drive, then delete the original files from the system drive. The batch file below works, with one glitch: I need to recreate the folder structure when the files are copied to the external drive. For example, if the file of interest is C:\foo\foo.txt, I need it to copy to a \foo directory on the external drive. I thought I had the xcopy parameters set to do that, but it's simply copying everything into one folder.

Next, I'd like to have some error handling in the batch file, in case some files aren't present.

Thanks a million for any help! Here's what I have so far...

@echo off
for /f "tokens=* delims=" %%a in ('type "D:\files.txt"') do xcopy /shrkvy "%%a" "D:\Reclamation"
echo All files copied to reclamation folder.
@echo off
for /f "tokens=* delims=" %%a in ('type "D:\files.txt"') do del "%%a"
echo All files deleted from device.
pause
1

1 Answer

I think what you want is something like this. If a file fails to be copied it is written to errors.txt and not deleted from the source. Successful copied filles are deleted from the source.

@echo off
set Source=D:\files.txt
set Destination=D:\Reclamation
SetLocal EnableDelayedExpansion
for /f "tokens=* delims=" %%a in ('type "%Source%"') do ( IF not exist "%Destination%%%~pa" md "%Destination%%%~pa" xcopy /shrkvy "%%a" "%Destination%%%~pa" IF NOT !ErrorLevel! EQU 0 (echo "%%a">>"Errors.txt") else (del /q "%%a") )
3

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like