Link to home
Start Free TrialLog in
Avatar of Damarado
Damarado

asked on

Batch script to delete folder content

I have a script that I run weekly and deletes the content of users sub folders. It goes through a text file called users.txt and deletes the folders content. The problem I have is that is also deletes sub folders less than a week old.

User  srogers  (main folder, where names are in .txt file)
               srogers-a1(subfolders in main folder)
              srogers-a2
              srogers-a3
             srogers-a4
              srogers-a5

I want the script to delete content  in the subfolders older than a week, but not touch any folders in the subfolders less than a week old.

This is the script.

@echo off
set UserList=D:\users.txt
set topLevel=D:\files\user_files
for /f "delims=" %%u in ('type "%UserList%"') do (
      cd /D "%topLevel%\%%~u"
      FOR /D %%a IN (*) DO (
            forfiles /P "%topLevel%\%%~u\%%a" /S /M *.* /D -7 /C "cmd /C  del @PATH"
            cd /D "%topLevel%\%%~u\%%a"
            for /f "delims=" %%i in ('dir /s /b /ad ^| sort /r') do  rd "%%i">NUL
      )
)
Avatar of reredok
reredok
Flag of Germany image

sorry I'm not a cmd expert, but i would solve your problem with powershell

first look at the logfile D:\logfile.log if all seem to be allright.
Get-ChildItem "D:\files\user_files" -Directory | Get-ChildItem -Include '*.*' -Recurse | where LastWriteTime -lt (Get-Date).AddDays(-7) | Out-File D:\logfile.log

Open in new window

after you verify the log file you can add | Remove-Item in the last pipe instead of | Out-File D:\logfile.log
ASKER CERTIFIED SOLUTION
Avatar of Arana (G.P.)
Arana (G.P.)

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Damarado
Damarado

ASKER

fixed issue, thanks