Purge Function - best way?

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
SIMMS7400
Posts: 475
Joined: 07 Jan 2016 07:47

Purge Function - best way?

#1 Post by SIMMS7400 » 10 Aug 2020 04:13

Hi Folks -

One can read for hours and hours online about the best way to purge files and folders (and sub directories). Everyone seems to have their own iteration.

This is what I came up with. Essentially, a path (less the trailing "\" is passed to a function and then I run a FORFILES over it to remove all files from the current and subdir's that match the specified age. Then I use the ROBOCOPY techniques to copy itself with the /S /MOVE switches to remove the empty folders.

Is this an OK approach?

Code: Select all

CALL :PURGE ""C:\Hyperion_Batch\Errors","C:\Hyperion_Batch\Logs","C:\Hyperion_Batch\Archives""

:PURGE
SET "PURGE=%~1"
FOR %%D IN ( %PURGE:,= % ) DO (
	
	SET "PDIR=%%~D"
	ECHO "!PDIR!" | FINDSTR /C:"Archive" >nul 2>&1 && ( SET "AGE=60" & GOTO BREAK )
	ECHO "!PDIR!" | FINDSTR /C:"Errors"  >nul 2>&1 && ( SET "AGE=30" & GOTO BREAK )
	ECHO "!PDIR!" | FINDSTR /C:"Logs"    >nul 2>&1 && ( SET "AGE=30" & GOTO BREAK )
	SET "AGE=30"
	
	:BREAK
	FORFILES /P "!PDIR!" /S /M *.* /D -!AGE! /C "CMD /C DEL @PATH"
	ROBOCOPY "!PDIR!" "!PDIR!" /S /MOVE
	
)
pause
GOTO :EOF
This seems to work on 2008+ servers and Win7+.

Compo
Posts: 506
Joined: 21 Mar 2014 08:50

Re: Purge Function - best way?

#2 Post by Compo » 10 Aug 2020 08:23

No it isn't! To begin with you shouldn't be using a label within the do portion of a for loop.

Would this not do essentially the same thing?

Code: Select all

CALL :PURGE "C:\Hyperion_Batch\Errors","C:\Hyperion_Batch\Logs","C:\Hyperion_Batch\Archives"

PAUSE
GOTO :EOF

:PURGE
SET "AGE=92"
FOR %%G IN (%*) DO (
	IF /I "%%~nxG" == "Archives" SET "AGE=60"
	IF /I "%%~nxG" == "Errors" SET "AGE=30"
	IF /I "%%~nxG" == "Logs" SET "AGE=30"
	SETLOCAL ENABLEDELAYEDEXPANSION
	FORFILES /P "%%~G" /S /D -!AGE! /C "CMD /C IF @ISDIR==FALSE DEL @PATH"
	ENDLOCAL
	ROBOCOPY "%%~G" "%%~G" /S /MOVE
)

Post Reply