1.

Solve : Delete files in dir2 that aren't in dir1 with a bat script?

Answer»

I wrote a somewhat simple batch script for updating files on service LAPTOPS from server that is working just FINE using xcopy. The only problem is, after a while, the laptops begin to accumulate unused files that were deleted from the server.

I imagine it's fairly simple to do, but I can't quite figure out how I can delete any file in one directory (destination/laptop) that does not exist in another directory (source/server). The other problem is, this MUST be able to work with Windows Vista and XP, so I can't just use robocopy /purge

Any help is appreciated!This should work.


@For /f "delims=" %%a in ('Dir /b dir2') do if not exist dir1/%%a del dir2/%%a
Awesome, that actually works
(I just had to add some quotes to account for spaces in file names)

Now how can I make that delete recursively through subdirectories (and delete an entire subdirectory if it is unique)?I think adding the /s switch after /b should do it for within subdirectories and maybe adding
& rd dir2/%%a

I can't test this, but just make sure the bat file is in the folder where both directories are located. Thank! I'm so close.

I'm 'kind of' having a problem with parsing the 'dir /b /s dir2'. It outputs the entire filename and path to %%a which will obviously not work for 'dir1/%%a'. My CURRENT solution 'works' but I'd like it to be a little more dynamic. This is what I have so far...

Code: [Select] :: IP address of the server ::
set SIP=127.0.0.1

:: Path to 'Data' folder on server ::
set SRC=%SIP%\c$\server\data

:: Path to 'Data' folder on destination computer ::
set DST=c:\laptop\data
.
.
.
For /F "tokens=4* delims=\" %%a in ('dir /b /s %DST%') do if not exist "\\%SRC%\%%a\%%b" del "%DST%\%%a\%%b"

This works for each of the 4 FOLDERS within %DST% (c:\laptop\data), but if there is another folder in one of those, it will not work because there are only 2 tokens in the command (del "%DST%\%%a\%%b"). I tried just adding '%%c' to that, but it just literally adds "%%c" to the command.

SO...essentially what I need, is to remove %DST% (c:\laptop\data) from the output of ('dir /b /s %DST%') so that %%a will just be \\...\ which will end up in the command > if not exist "\\%SRC%\%%a" del "%DST%\%%a"

I know that was a bit of explanation and a lot of %'s, so please ask clarification questions



Discussion

No Comment Found