trouble with deleting in a loop

Pretty new scripter so sorry if this is lame. As part of a larger script, i’m trying to delete old files out of a folder. I thought this would work but it errors out because, assumedly, it’s deleting the very files it’s using to count. i can’t imagine this task isn’t a pretty common one though so i was hoping someone out there had a solution.


tell application "Finder"
tell MYfolder
	set filecount to count of files
	repeat with i from 1 to filecount
		set currentfile to item i
		if (current date) - (modification date of currentfile) is greater than 172800 then
			delete currentfile
		end if
	end repeat
end tell
end tell

any help or general mocking of my ignorance is more than welcome. thanks.

I’m sure someone has a slicker way than this, but why not count backwards?

repeat with i from filecount to 1 by -1
  • Dan T.

i didn’t count backwards cause i’m an idiot and didn’t know you could. someone might have a slicker way but your way is perfect. thanks a bunch and sorry for being the slow kid in class.

There’s no way it’s idiotic not to know that (did I say that right? I meant it in the best possible sense) - if you’re new to scripting it’s not at all obvious that you can do that… :smiley:

You may not get the results you are looking for with your code because you count the files but then you reference the items. Items encompass both files and folders. You’re better off first getting the file list and then iterating through that. Also, you’ll save some time by getting the current date only once and assigning it to a variable:

Jon


[This script was automatically tagged for color coded syntax by Convert Script to Markup Code]

Then again, depending on which OS version you’re running, you can:

tell application "Finder"
set cutoffdate to (current date) - 172800
delete every file of folder "Macintosh HD:My Folder" whose modification date is less than cutoffdate
end tell

Again… with a UNIX backend, you can do shell script that is much faster…:

cd into the desired directory and:
find . -mtime +30 -exec rm {};


You can use the -print option to see what would be deleted if you’d rather. Beware… this is powerful and can step through directories recursively without having to prompt for responses, etc.

-RM