Jump to content

Script to Remove FOLDERS older than X days


Recommended Posts

So I have a couple directories where backups are created. The names of the folders are not uniform in any way (that I can see)

So I need to write something that can look at the modified/created date of the folder and remove it if its older than X days.

I have tried using a Forfiles command, which seems super easy, but I cant get it to work right on server 2003. I imgine most of the examples I have found are for windows 7. Does autoit have an easy way to do this?

Link to comment
Share on other sites

  • Moderators

wisem2540,

FileGetTime also works on folders - so now you can find out when they were created.

Then _DateDiff should allow you to find out how many days ago they were created - but look carefully at the format you require as you will have to modify the return from FileGetTime (StringMid is what you need).

As to listing the folders in the first place, _FileListToArray will do that - but if you need to get to subfolders as well, take a look at the RecFileListToArray UDF in my sig. :huh:

Give it a go yourself - you know where we are if you run into problems. :D

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

That looks to be slightly more complicated than I intended it to be. In any event, I am not against learning something new....

Just so you are aware, I do not have programming knowledge when it comes to simple things like Arrays.

Anyway, I put the first command in FileGetTime and it wants a file name. So I put *.* (because I want folders) but it doesnt appear I have a way to test this to see if it works....

Sorry to sound like a total noob here...

Link to comment
Share on other sites

  • Moderators

wisem2540,

a total noob here

We all were at one time...so we will do this in stages. :huh:

FileGetTime requires a specific file/foldername as a parameter - *.* will not work. :D

_FileListToArray will list folders if they are all within a single folder - is that the case? :D

If so we can move on to how to loop through the returned list. :)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

I have a folder called C:Test

Inside of it I have folders with random names that are full of old backups. I need to look at these random named folders and eventually delete the ones that are 3 days or more old (so my drive doesnt fill up)

So my problem is, I cant really specify one folder because they are random. Would I specify TEST?

thanks for the help

Link to comment
Share on other sites

  • Moderators

wisem2540,

Run this script and see if you can understand why it does what it does: :D

#include <File.au3>
#include <Array.au3>

Global $aList = _FileListToArray("C:Test", "*", 2)

_ArrayDisplay($sList)

Ask if you have any questions - but make sure you read the Help file first to see what the various parameters mean. :huh:

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

  • Moderators

wisem2540,

After I fixed the typo, it works great

Oops! :D

So now we loop through the array and get the date of each folder: :)

#include <File.au3>

; put the root in a variable
$sRoot = "C:Test"

; We can use that variable here
Global $aList = _FileListToArray($sRoot, "*", 2)

; This is a loop that runs from 1 to the number of items listed in the first element of the returned  array
For $i = 1 To $aList[0]
    ; Here we display the folder name taken from the array and use FileGetTime to get the datetimegroup
    MsgBox(0, "Folder date", $sRoot & "" & $aList[$i] & @CRLF & @CRLF & FileGetTime($sRoot & "" & $aList[$i], 0, 1))
Next

Again ask if you cannot understand what is happening. :huh:

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

Well it works...and I see message boxes. So most of the code I get.... but not really....

So I dont get the @CRLF reference, nor do I really get anything after the msgbox command....

also, it appears to also include the time... any way to surpress that? I only ask because it makes it hard to read...

In comes accross like this... 20120625140425

Obviously 140425 refers to time, but I dont really need that...

Edited by wisem2540
Link to comment
Share on other sites

@CRLF just means it's performing a carriage-return line-feed. Which is why you see the gap between lines of text in the msgbox.

There's still a couple additional steps you need. Can you guess what to do next?

(this is like a Disney Channel learning program XD)

Edited by mechaflash213
Spoiler

“Hello, ladies, look at your man, now back to me, now back at your man, now back to me. Sadly, he isn’t me, but if he stopped using ladies scented body wash and switched to Old Spice, he could smell like he’s me. Look down, back up, where are you? You’re on a boat with the man your man could smell like. What’s in your hand, back at me. I have it, it’s an oyster with two tickets to that thing you love. Look again, the tickets are now diamonds. Anything is possible when your man smells like Old Spice and not a lady. I’m on a horse.”

 

Link to comment
Share on other sites

  • Moderators

wisem2540,

Look in the Help file - did I say that already? :D

MsgBox(0, "Folder date", $sRoot & "" & $aList[$i] & @CRLF & @CRLF & FileGetTime($sRoot & "" & $aList[$i], 0, 1))
       ^   ^             ^
       |   |             |
    flag,  title,        text

The text is made up as follows:

$sRoot                                         ; the variable containing the root folder
&                                              ; this adds the variosu parts together - "concatenation"
""                                            ; other wise we do not get a proper path
& 
$aList[$i]                                     ; the folder name from the array
& 
@CRLF                                          ; a newline
& 
@CRLF 
& 
FileGetTime($sRoot & "" & $aList[$i], 0, 1))  ; And the result of the function
            ^                          ^  ^
            |                          |  | 
            filename              option  format

Over to you. :huh:

M23

Edit:

mechaflash213,

Is that you volunteering to take over? :)

Edited by Melba23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

  • Moderators

wisem2540,

No, you can do the work inside the loop for each folder in turn. :D

Once you have the returned value from FileGetTime (YYYYMMDDHHMMSS) you will need to reformat it to match the required format for _DateDiff (YYYY/MM/DD as you are only lookign at the days). As you can see you will need to add in the "/" characters - as I mentioned above, StringMid will be the way to go here. :huh:

Using the Help file example for StringMid, just try and convert this 20120626211300 into this 2012/06/26. See how you get on. :)

M23

Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Link to comment
Share on other sites

or just let FileGetTime() output it to an array, and format the array parts into a string XD.

If you're using SciTE to do your coding (which you should be... ) as you type a function like FileGetTime, mouseover it, F1, and it will show you the function's syntax and what the function returns.

@Melba and No =P

Edited by mechaflash213
Spoiler

“Hello, ladies, look at your man, now back to me, now back at your man, now back to me. Sadly, he isn’t me, but if he stopped using ladies scented body wash and switched to Old Spice, he could smell like he’s me. Look down, back up, where are you? You’re on a boat with the man your man could smell like. What’s in your hand, back at me. I have it, it’s an oyster with two tickets to that thing you love. Look again, the tickets are now diamonds. Anything is possible when your man smells like Old Spice and not a lady. I’m on a horse.”

 

Link to comment
Share on other sites

wisem2540

; http://www.autoitscript.com/forum/topic/141609-old-files/#entry996385"]http://www.autoitscript.com/forum/topic/141609-old-files/#entry996385

#include <Array.au3>
#include <FileOperations.au3>

Global $TimeDiff = 3600 * 24 * 3
$TimeCurrent = _NowCalc()

$FolderList = _FO_FolderSearch(@TempDir, '*')
_ArrayDisplay($FolderList, 'Folder = *')

$c = 0
For $i = 1 To $FolderList[0]
    $t = FileGetTime($FolderList[$i], 1)
    $sTime = $t[0] & '/' & $t[1] & '/' & $t[2] & ' ' & $t[3] & ':' & $t[4] & ':' & $t[5]
    If _DateDiff('s', $sTime, $TimeCurrent) > $TimeDiff Then
        $c += 1
        $FolderList[$c] = $FolderList[$i]
    EndIf
Next
ReDim $FolderList[$c + 1]
$FolderList[0] = $c
_ArrayDisplay($FolderList, '>3')

If MsgBox(4, '???', 'FileRecycle ?') = 6 Then
    $err = ''
    For $i = 1 To $FolderList[0]
        If Not FileRecycle($FolderList[$i]) Then
            $err &= $FolderList[$i] & @CRLF
        EndIf
    Next
    If $err Then MsgBox(0, 'Error', $err)
EndIf
Edited by AZJIO
Link to comment
Share on other sites

#include <Array.au3>
#include <File.au3>
#include <Date.au3>

; put the root in a variable
$sRoot = "C:Test"

; Retrieve a list of all the folders in $sRoot, and store that list as an array in $aList
Global $aList = _FileListToArray($sRoot, "*", 2) ; _FileListToArray("path" [, "Filter" [, Flag]])
; Look at what _FileListToArray() puts into $aList
; You can delete the below line after seeing the output for the first time
_ArrayDisplay($aList)

; This is a loop that runs from 1 to the number of items listed in the first element of the returned  array
For $i = 1 To $aList[0]
    ; For each folder, get the modified date/time and store its individual parts in array $aDate
    $aDate = FileGetTime($sRoot & $aList[$i], 0, 0) ; FileGetTime("filename" [, option [, format]])

    ; Look at what FileGetTime() puts into $aDate
    ; You can delete the below line after seeing the output for the first time
    _ArrayDisplay($aDate)

    ; Build the properly formatted date string for _DateDiff()'s needs
    $sDate = $aDate[0] & "/" & $aDate[1] & "/" & $aDate[2] ;0 index stores the year, 1 index stores month, 2 index stores day

    ; Look at what we made into $sDate
    ; You can delete the below line after seeing the output for the first time
    msgbox(0,"Check Output", $sDate)

    ; Use _DateDiff() to see if the difference is greater than 3 days, and if it's true, then delete the folder and all its subfolders
    If _DateDiff("D", $sDate, _NowCalcDate()) > 3 Then DirRemove($sRoot & $aList[$i], 1)
Next

Now where do I send my bill for this $100 course?

EDIT: Removed my $sToday string and used _NowCalcDate() directly in _DateDiff() function

Edited by mechaflash213
Spoiler

“Hello, ladies, look at your man, now back to me, now back at your man, now back to me. Sadly, he isn’t me, but if he stopped using ladies scented body wash and switched to Old Spice, he could smell like he’s me. Look down, back up, where are you? You’re on a boat with the man your man could smell like. What’s in your hand, back at me. I have it, it’s an oyster with two tickets to that thing you love. Look again, the tickets are now diamonds. Anything is possible when your man smells like Old Spice and not a lady. I’m on a horse.”

 

Link to comment
Share on other sites

  • 3 weeks later...

#include <Array.au3>
#include <File.au3>
#include <Date.au3>

; put the root in a variable
$sRoot = "C:Test"

; Retrieve a list of all the folders in $sRoot, and store that list as an array in $aList
Global $aList = _FileListToArray($sRoot, "*", 2) ; _FileListToArray("path" [, "Filter" [, Flag]])
; Look at what _FileListToArray() puts into $aList
; You can delete the below line after seeing the output for the first time
_ArrayDisplay($aList)

; This is a loop that runs from 1 to the number of items listed in the first element of the returned array
For $i = 1 To $aList[0]
; For each folder, get the modified date/time and store its individual parts in array $aDate
$aDate = FileGetTime($sRoot & $aList[$i], 0, 0) ; FileGetTime("filename" [, option [, format]])

; Look at what FileGetTime() puts into $aDate
; You can delete the below line after seeing the output for the first time
_ArrayDisplay($aDate)

; Build the properly formatted date string for _DateDiff()'s needs
$sDate = $aDate[0] & "/" & $aDate[1] & "/" & $aDate[2] ;0 index stores the year, 1 index stores month, 2 index stores day

; Look at what we made into $sDate
; You can delete the below line after seeing the output for the first time
msgbox(0,"Check Output", $sDate)

; Use _DateDiff() to see if the difference is greater than 3 days, and if it's true, then delete the folder and all its subfolders
If _DateDiff("D", $sDate, _NowCalcDate()) > 3 Then DirRemove($sRoot & $aList[$i], 1)
Next

Now where do I send my bill for this $100 course?

EDIT: Removed my $sToday string and used _NowCalcDate() directly in _DateDiff() function

I tried this script because it was very well-documented and because it looked like it would achieve my own goals very nicely (that being to purge all folders greater than 3 days in a predesignated location). Unfortunately, every time I run it I get the following error:

==========================================================

[PATH TO AU3 FILE] (15) : ==> Subscript used with non-Array variable.:

$sDate = $aDate[0] & "/" & $aDate[1] & "/" & $aDate[2]

$sDate = $aDate^ ERROR

==========================================================

The '[PATH TO AU3 FILE] is the local path to the .au3 file I'm testing with (the file into which I copied your code).

I did some searching on this, and I'm not sure what's causing the issue. Some people say that empty directories will do it, but all of my folders have content. Right now I'm only testing against a local folder with some generic subfolders and files, so this isn't in production yet.

Even though most of what's in the script is over my head, it seems to make sense. I'm really not sure why I'm getting this error.

Any ideas?

Thanks,

Bob

Edited by bgruett
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...