I need an AppleScript. The script’s function is to remove (delete) ALL empty Directory Folders in a Directory Folder Structure. If there is a file in any folder - the file and the enclosing folder must NOT be deleted. I define an empty folder as one that does not have Files OR Folders inside of it.
The script should allow a User to navigate using the Finder to the directory where the script will operates on.
(*
delete empty folders
2018-12-01
*)
----------------------------------------------------------------
use AppleScript version "2.4"
use framework "Foundation"
use scripting additions
----------------------------------------------------------------
script o
-- store the list of folders here so it will not be written on disk
property theFolders : {}
end script
Germaine()
#=====
on Germaine()
-- Define the folder to clean
set targetDir to choose folder
my removeEmptyFolders:targetDir
end Germaine
#=====
on removeEmptyFolders:targetDir
set POSIXPath to POSIX path of targetDir
set theFolderURL to current application's NSURL's fileURLWithPath:POSIXPath
set NSFileManager to a reference to current application's NSFileManager's defaultManager()
-- extract the list of items stored in the folder skipping the invisibles
set theURLs to (NSFileManager's enumeratorAtURL:theFolderURL includingPropertiesForKeys:{} options:4 errorHandler:(missing value))'s allObjects()
if theURLs is equal to missing value then error (theError's localizedDescription() as text)
set o's theFolders to {}
repeat with aURL in theURLs
set {theResult, theValue, theError} to (aURL's getResourceValue:(reference) forKey:(current application's NSURLIsDirectoryKey) |error|:(reference))
if theResult as boolean is false then error (theError's |localizedDescription|() as text) number (theError's code() as integer)
# build a list of URLs describing folders
if theValue as boolean then copy aURL to end of o's theFolders
end repeat
set (o's theFolders) to reverse of (o's theFolders)
repeat with aURL in o's theFolders
-- aURL point to a folder
-- extract the list of items stored in this folder skipping the invisibles
set theURLs to (NSFileManager's enumeratorAtURL:aURL includingPropertiesForKeys:{} options:4 errorHandler:(missing value))'s allObjects()
if (count theURLs) = 0 then
-- the folder is empty, delete it
set theResult to (NSFileManager's removeItemAtURL:aURL |error|:(missing value))
end if
end repeat
end removeEmptyFolders:
#=====
Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) lundi 6 janvier 2020 13:37:26