Tom Wildt
Tom Wildt

Reputation: 113

Script to move folders and files with minage

I'm using robocopy to delete folders/files from a directory.

The script:

  SET source1=c:\source
  SET destination=F:\destination
  SET switch1=/r:10 /w:1 /e /create /minage:10 /mt /LOG:F:\logs\backup.log

  FOR /d %%i IN ("%source1%\*") DO ROBOCOPY "%%i" "%destination%\%%~nxi" %switch1%
  FOR /d %%p IN ("%source1%\*") DO RMDIR "%%p" /s /q
  FOR /d %%q IN ("%destination%\*") DO RMDIR "%%q" /s /q

Source directory looks like this:

c:\source\directory\file1.txt (12 days old)

c:\source\directory2\file2.txt (5 days old)

My problem is this line in the script:

FOR /d %%p IN ("%source1%\*") DO RMDIR "%%p" /s /q

That line is not just RMDIR the directory's that were copied from source, its removing them all. And a note, I cannot use /move as it will delete the source directory. If I use /mov it won't delete all the subdirectories.

Any thoughts what I have wrong here? Thanks in advance.

EDIT: I am including the source directory dir /tw /s information for troubleshooting. The ABT folder is the folder that should be deleted.

 Directory of C:\

09/27/2016  03:08 PM    <DIR>    .
09/27/2016  12:10 PM    <DIR>    ..
09/27/2016  03:09 PM    <DIR>    New Folder
06/25/2014  05:47 AM    <DIR>    abt
               0 File(s)

 Directory of C:\New folder

09/27/2016  03:09 PM    <DIR>
09/27/2016  03:08 PM    <DIR>
09/27/2016  03:09 PM
               1 File(s)

 Directory of C:\abt

06/25/2014  05:47 AM    <DIR>
09/27/2016  03:08 PM    <DIR>
03/20/2014  10:08 AM
06/25/2014  05:47 AM
04/28/2014  02:33 PM
05/20/2014  10:47 AM    <DIR>
02/18/2014  07:24 PM
05/20/2014  10:51 AM
               5 File(s)

 Directory of C:\abt\Scripts

05/20/2014  10:47 AM    <DIR>
06/25/2014  05:47 AM    <DIR>
10/02/2012  11:18 AM
02/02/2012  12:16 PM
02/17/2012  11:32 AM

Upvotes: 0

Views: 1358

Answers (1)

MC ND
MC ND

Reputation: 70923

If robocopy can handle everything except folder removal, the only thing you need to do is ensure robocopy will not be able to delete the folder.

This can be done simply by setting the source folder as the current active directory. You can not remove a folder that is in use.

SET "source1=c:\source"
SET "destination=F:\destination"
SET "switch1=/move /e /create /minage:10 /r:10 /w:1 /LOG+:F:\logs\backup.log"

pushd "%source1%" && (
    robocopy . "%destination%" %switch1%
    popd
)

The only drawback is that robocopy will show an error saying it can not delete the source folder because it is in use.

Upvotes: 2

Related Questions