简体   繁体   中英

Delete all files in directory except in one subdirectory

I have this script:

    forfiles /p "C:\Hello" /m *.* /s /d -5 /c "cmd /c if /i not @path==C:\Hello\Dontdelete del @file"

I'm trying to delete every file older than 5 days in C:\\Hello except for files that are in C:\\Hello\\Dontdelete or any directory within this path.

Currently everything is getting deleted when I use the above script.

Thanks!

I do not know much about it, but I think you should make a lopping for every 5 days, the script did a check to see if there are files in the folder C :/ Hello, if yes, the script clears, if not, it does nothing. Search about it.

The fundamental problem is that @path is the full pathname - including the filename+extension, and quoted and @file is the filename+extension, also quoted. In consequence, the if statement as constructed can't be manipulated to work as anticipated.

Here's a way to get it working (I've made a few changes to suit my system which should be easy to manipulate to suit yours)

@ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
forfiles /p "%sourcedir%" /m *.* /s /d -6 /c "cmd /c call %cd%\selectdel @PATH"
GOTO :EOF

I set up selectdel as a batch in my current directory. No doubt it would be fine on the path, or simply forced as I have with the %cd%\\ .

selectdel.bat

@echo off
setlocal
if /i not "%~dp1"=="%sourcedir%\Dontdelete\" echo DEL %1
GOTO :eof

Obviously, I've simply echo ed the del command - in case of accidents...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM