# Solved: Batch File to delete old Folders...



## kenne75 (Aug 3, 2009)

My helpdesk software is writing a backup file to a directory I created on the hard drive. It creates a new directory every night at midnight, it only stores 7 nights worth so I have a directory call C:\Backup with 7 folders in there being named 1-7. I need some help creating a batch file that will only keep the 2 newest folders as it is taking up to much space on the Server. If it makes a difference I am running Windows Server 2003. Any help would be greatly appreciated. Help me Please!


----------



## kenne75 (Aug 3, 2009)

Here is the Batch I have created but for some reason isn't working. I get the prompt but when I say all the directory still exists. 

:: User Variables
:: Set this to the number of folders you want to keep
Set _NumtoKeep=1
:: Set this to the folder that contains the folders to check and delete
Set _Path=C:\Program Files\SysAidServer\backup
If Exist "%temp%\tf}1{" Del "%temp%\tf}1{"
PushD %_Path%
Set _s=%_NumtoKeep%
If %_NumtoKeep%==1 set _s=single
Echo Please wait, searching for folders other than the %_s% most recent
For /F "tokens=* skip=%_NumtoKeep%" %%I In ('dir "%_Path%" /AD /B /O-D /TW') Do (
If Exist "%temp%\tf}1{" (
Echo %%I:%%~fI >>"%temp%\tf}1{"
) Else (
Echo.>"%temp%\tf}1{"
Echo Do you wish to delete the following folders?>>"%temp%\tf}1{"
Echo Date Name>>"%temp%\tf}1{"
Echo %%I:%%~fI >>"%temp%\tf}1{"
))
PopD
If Not Exist "%temp%\tf}1{" Echo No Folders Found to delete & Goto _Done
Type "%temp%\tf}1{" | More
Set _rdflag= /q
:_Prompt1
Set /P _resp=Delete All, None, or Prompt for each (A/N/P)?
If /I "%_resp:~0,1%"=="N" Goto _Done
If /I "%_resp:~0,1%"=="A" Goto _Removeold
If /I NOT "%_resp:~0,1%"=="P" (Echo (A/N/P only please)&Goto _Prompt1
Set _rdflag=
:_Removeold
For /F "tokens=1* skip=3 Delims=:" %%I In ('type "%temp%\tf}1{"') Do (
If "%_rdflag%"=="" Echo Deleting
rd /s%_rdflag% "%%J")
:_Done
If Exist "%temp%\tf}1{" Del "%temp%\tf}1{"
HTH


----------



## Squashman (Apr 4, 2003)

Double Post
http://forums.techguy.org/dos-pda-other/848854-batch-file-delete-old-folders.html


----------

