File move into subfolders on distant server

I fixed this problem as need. No I debug other mistakes

NOTE to OP: in 2) step you describe. Renaming of original file is equivalent to moving it immediately to Rip directory. So, don’t do that. Instead, duplicate it to Rip directory and rename the duplicate. NOT COPY but duplicate command should be used.

As insomnia strike, I built a more complete code.

----------------------------------------------------------------
use AppleScript version "2.5"
use framework "Foundation"
use script "FileManagerLib" version "2.2.2"
use scripting additions
----------------------------------------------------------------
property forTests : true #  during tests I use copy object so the original files remain in place

tell application "Finder"
	activate -- Bring to the front to display the following dialogs.
	
	set sourceDirectory to POSIX path of (choose folder with prompt "Select the folder containing the subfolders containing the file(s):")
	
	set destinationDirectory to POSIX path of (choose folder with prompt "Select a destination for the renamed file(s):")
end tell

# Build a list of files embedded in sourceDirectory
set workingFiles to objects of sourceDirectory result type paths list with searching subfolders without include folders and include invisible items

set p2d to path to desktop as text
set reportPath to p2d & "myLog.txt"
my writeto(reportPath, "", «class utf8», false) # Create/Clean the log file

# build the folder used as workspace
set tempFolder to POSIX path of (path to temporary items) # Edit to fit your needs

repeat with aFile in workingFiles
	if aFile ends with ".pdf" then
		try
			# Extract the relevant components of the path of the file
			set components to my decoupe(aFile, "/")
			set partialPath to my recolle(items -4 thru -3 of components, "/") --> "D1/D2"
			set lateSubFolder to item -2 of components --> "D3"
			set newNamePdf to my recolle(items -4 thru -1 of components, "_") --> "D1_D2_D3_oldName.pdf"
			set newNamePpm to (text 1 thru -3 of newNamePdf) & "pm" --> "D1_D2_D3_oldName.ppm"
			# Create the destination subfolders if they aren't available
			set finalDest to (create folder at (destinationDirectory & partialPath) use name lateSubFolder) & "/" --> "xxx/D1/D2/D3"
			# Duplicate the file to the temp folder so it will remain available if something fail during the process
			set tempPDF to copy object aFile to folder tempFolder new name newNamePdf with replacing and return path
			#log result
			my writeto(reportPath, my horoDateur() & " The file “" & aFile & "” is duplicated as “" & tempPDF & "”" & linefeed, «class utf8», true) # Write in the log file
			
			# Now fake "Caldera RIP" code 
			
			set tempPpm to tempFolder & newNamePpm
			# For safe, delete such Ppm if it already exists
			if exists object tempPpm then remove object tempPpm
			# Now we may rename. Returning the path was coded for tests, not needed in working script
			rename object tempPDF to name newNamePpm # with return path
			# log result
			my writeto(reportPath, my horoDateur() & " The file “" & tempPDF & "” is converted as “" & tempPpm & "”" & linefeed, «class utf8», true) # Write in the log file
			
			
			# Move the Ppm file to final location.
			
			set finalPpm to move object tempPpm to folder finalDest with replacing and return path --> "xxx/D1/D2/D3/D1_D2_D3_oldName.ppm"
			#log result
			my writeto(reportPath, my horoDateur() & " The document is stored as “" & finalPpm & "”" & linefeed & linefeed, «class utf8», true) # # Write in the log file
			# Here the process ended flawlessly so we may delete the original
			if not forTests then remove object aFile
			
		on error e number n
			
			my writeto(reportPath, my horoDateur() & " Error : " & e & " number# " & n & " The original file “" & aFile & ". remains available." & linefeed & linefeed, «class utf8», true) # Write in the log file
		end try
	end if
end repeat

#=====

on decoupe(t, d)
	local oTIDs, l
	set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
	set l to text items of t
	set AppleScript's text item delimiters to oTIDs
	return l
end decoupe

#=====

on recolle(l, d)
	local oTIDs, t
	set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
	set t to l as text
	set AppleScript's text item delimiters to oTIDs
	return t
end recolle

#=====

(*
Handler borrowed to Regulus6633 - http://macscripter.net/viewtopic.php?id=36861
*)
on writeto(targetFile, theData, dataType, apendData)
	-- targetFile is the path to the file you want to write
	-- theData is the data you want in the file.
	-- dataType is the data type of theData and it can be text, list, record etc.
	-- apendData is true to append theData to the end of the current contents of the file or false to overwrite it
	try
		set targetFile to targetFile as «class furl»
		set openFile to open for access targetFile with write permission
		if not apendData then set eof of openFile to 0
		write theData to openFile starting at eof as dataType
		close access openFile
		return true
	on error
		try
			close access targetFile
		end try
		return false
	end try
end writeto

#=====

on horoDateur()
	set theFormatter to current application's NSDateFormatter's new()
	theFormatter's setDateFormat:"yyyy-MM-dd HH:mm:ss"
	return (theFormatter's stringFromDate:(current date)) as text
end horoDateur

#=====

@KniazidisR

You made a mixture of fileManagerLib syntax and Finder’s one.

set ripFile to duplicate aFile to RipDirectory with newName – all this was THE FIRST PART OF JOB is a wrong instruction.
There is no duplicate command in FileManagerLib.
There is a create duplicate one but it doesn’t accept the parameter with newName
The correct syntax would be :
set ripFile to copy object aFile to folder RipDirectory new name newName with return path # for safe add “and replacing

The instruction :
move ripFile to destinationDirectory is wrong too
It would be :
move object ripFile to folder destinationDirectory

I hope that I forgot nothing. Now I will retry to sleep.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) mardi 6 aout 2019 23:01:41

I corrected an error and added code writing a log file on the desktop.

I was tested and changed all the script. This works fine and is shorter:


----------------------------------------------------------------
use AppleScript version "2.5"
use framework "Foundation"
use script "FileManagerLib" version "2.2.1"
use scripting additions
property RipDirectory : path to desktop
----------------------------------------------------------------

tell application "Finder"
	activate -- Bring to the front to display the following dialogs.
	set sourceDirectory to POSIX path of (choose folder with prompt "Select the folder containing the subfolders containing the file(s):")
	set destinationDirectory to POSIX path of (choose folder with prompt "Select a destination for the renamed file(s):")
end tell

# Build a list of files embedded in sourceDirectory
set workingFiles to objects of sourceDirectory result type files list with searching subfolders without include folders and include invisible items

repeat with aFile in workingFiles
	
	-- FIND and REMEMBER NAMES of D1,D2,D3 folders
	tell application "System Events"
		set parentFolder to container of (aFile as alias)
		set parentFolderName to name of parentFolder -- "D3"
		set grandParentFolder to container of parentFolder
		set grandParentFolderName to (name of grandParentFolder) -- "D2"
		set rootFolder to container of grandParentFolder
		set rootFolderName to (name of rootFolder) -- "D1"
	end tell
	tell application "Finder"
		set ripFile to duplicate aFile to RipDirectory -- all this was THE FIRST PART OF JOB
		set ripFile to POSIX path of (ripFile as alias)
	end tell
	
	-- HERE GOES SECOND PART -- CONVERTING WITH "Caldera RIP". I don't know how you do this.
	-- It should process ripFile instead of aFile 
	
	-- The 3rd PART OF JOB
	set partialPath to rootFolderName & "/" & grandParentFolderName -- "D1/D2"
	set finalDest to create folder at (destinationDirectory & "/" & partialPath) use name parentFolderName --> "xxx/D1/D2/D3"
	move object ripFile to folder finalDest
	
end repeat

‘object’ isn’t a Finder term.

Thanks. OK, I fixed the error and now my last script works as I wanted.

Hello everyone,

Thank you for all your answers, it allows me to progress.

However, I think I am going to use two separate scripts.
The Rip Caldera being an intermediate process well apart, there can be no link between the three stages of Workflow.
(Otherwise it would be necessary to use a database and then manage it, which seems very complicated for my skills.)

I will do some tests and come back and show them to you.

GK

I edited message #16

I made a correction and added code writing a log file on the desktop.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) mercredi 7 aout 2019 11:21:57

Hi,

Here are my two scripts between the Rip Caldera Proccess. (www.caldera.com for the curious)
I start with the example of Yvan, because I like the functions “decoupe” and “recolle”.
The part I added or modified is a lot less elegant, but seems to work as desired.

I still have to find how to write in the log file the files in error (files deposited in the source folder, but impossible to move for example - corrupted file …)

And I must also delete the folders D1, D2 and D3 not used for more than 45 days.

GK

Script 1

# Code Yvan/GK Script 1 --> Pdf vers Caldera

----------------------------------------------------------------
use AppleScript version "2.5"
use framework "Foundation"
use script "FileManagerLib" version "2.2.2"
use scripting additions
----------------------------------------------------------------
property forTests : true #  during tests I use copy object so the original files remain in place

# Working Folders
set sourceDirectory to POSIX path of ("Macintosh HD:Users:dupont:Desktop:Entree:")
set logDirectory to POSIX path of ("Macintosh HD:Users:dupont:Desktop:Logs:")
set destinationDirectory to POSIX path of ("Macintosh HD:Users:dupont:Desktop:Caldera:")

# Date use to create one log file / month
set theDate to (current date)
set y to text -4 thru -1 of ("0000" & (year of theDate))
set m to text -2 thru -1 of ("00" & ((month of theDate) as integer))
set d to text -2 thru -1 of ("00" & (day of theDate))
set mn to time string of (current date) -- ajoute les minutes et secondes

set theDate to y & "-" & m & "-" & d & "-" & mn

# create one log file / month
set reportPath to logDirectory & "Log_" & y & "_" & m & ".txt"
my writeto(reportPath, "", «class utf8», false) # Create/Clean the log file

# Build a list of files embedded in sourceDirectory
set workingFiles to objects of sourceDirectory result type paths list with searching subfolders without include folders and include invisible items

repeat with aFile in workingFiles
	# Extract the relevant components of the path of the file
	set components to my decoupe(aFile, "/")
	set partialPath to my recolle(items -4 thru -3 of components, "/") --> "D1/D2"
	set lateSubFolder to item -2 of components --> "D3"
	set newName to my recolle(items -4 thru -1 of components, "_") --> "D1_D2_D3_oldName.pdf" # ADDED
	
	# Create the destination subfolders if they aren't available
	--set finalDest to create folder at (destinationDirectory & "/" & partialPath) use name lateSubFolder --> "xxx/D1/D2/D3"
	# Move the file
	if forTests then
		copy object aFile to folder destinationDirectory new name newName 
		#log result
		my writeto(reportPath, my horoDateur() & " - PDF, ajout correct sur RIP Caldera:  " & newName & linefeed, «class utf8», true) # Write in the log file
		
	else
		move object aFile to folder finalDest new name newName 
		#log result
		my writeto(reportPath, my horoDateur() & " - PDF, ajout correct sur RIP Caldera:  " & newName & linefeed, «class utf8», true) # Write in the log file
		
	end if
end repeat

#======

-- TODO: GERER LA SUPPRESSION DES DOSSIERS D1/D2/D3 VIEUX DE PLUS DE 45 JOURS

--	--supprime les dossiers vieux de plus de 45 jours
--			if (creation date of (info for D3 ) < (current date) - 45 * days) then
--				
--				try
--					open for access FichLog with write permission
--					write theDate & " - Dossier commande ancien supprime :  " & Dos_3 & return to file the FichLog starting at eof -- écrire le message en fin de fichier-
--					close access FichLog
--				on error
--				try
--						close access file the FichLog
--					end try
--				end try
--				
--			tell application "Finder" to delete D3

--> Idem for D2 and D1

#=====

on decoupe(t, d)
	local oTIDs, l
	set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
	set l to text items of t
	set AppleScript's text item delimiters to oTIDs
	return l
end decoupe

#=====

on recolle(l, d)
	local oTIDs, t
	set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
	set t to l as text
	set AppleScript's text item delimiters to oTIDs
	return t
end recolle

#=====

on writeto(targetFile, theData, dataType, apendData)
	-- targetFile is the path to the file you want to write
	-- theData is the data you want in the file.
	-- dataType is the data type of theData and it can be text, list, record etc.
	-- apendData is true to append theData to the end of the current contents of the file or false to overwrite it
	try
		set targetFile to targetFile as «class furl»
		set openFile to open for access targetFile with write permission
		--if not apendData then set eof of openFile to 0
		write theData to openFile starting at eof as dataType
		close access openFile
		return true
	on error
		try
			close access targetFile
		end try
		return false
	end try
end writeto

#=====

on horoDateur()
	set theFormatter to current application's NSDateFormatter's new()
	theFormatter's setDateFormat:"yyyy-MM-dd HH:mm:ss"
	return (theFormatter's stringFromDate:(current date)) as text
end horoDateur

#=====

#================
Rip Caldera Process
#================

Script2

# Code Yvan/GK Script 2  --> Caldera-ppm vers Serveur

----------------------------------------------------------------
use AppleScript version "2.5"
use framework "Foundation"
use script "FileManagerLib" version "2.2.2"
use scripting additions
----------------------------------------------------------------
property forTests : true #  during tests I use copy object so the original files remain in place

# Working Folders	
set sourceDirectory to POSIX path of ("Macintosh HD:Users:dupont:Desktop:CalderaPPM:")
set logDirectory to POSIX path of ("Macintosh HD:Users:dupont:Desktop:Logs:")
set destinationDirectory to POSIX path of ("images:0_PPM:") -- Folder on remote server -- local folder for test("Macintosh HD:Users:dupont:Desktop:0_PPM:") --

# Date use to create one log file / month
set theDate to (current date)
set y to text -4 thru -1 of ("0000" & (year of theDate))
set m to text -2 thru -1 of ("00" & ((month of theDate) as integer))
set d to text -2 thru -1 of ("00" & (day of theDate))
set mn to time string of (current date) -- ajoute les minutes et secondes

set theDate to y & "-" & m & "-" & d & "-" & mn

# create one log file / month
set reportPath to logDirectory & "Log_" & y & "_" & m & ".txt"
my writeto(reportPath, "", «class utf8», false) # Create/Clean the log file

# Build a list of files embedded in sourceDirectory
set workingFiles to objects of sourceDirectory result type paths list without searching subfolders and include invisible items --include folders and include invisible items

repeat with aFile in workingFiles
	# Extract the relevant components of the path of the file
	set components to my decoupe(aFile, "/")
	# Extract the relevant components of the file
	set components to item -1 of components
	set components to my decoupe(components, "_")
	set nbcomponents to (number of components)
	
	set partialPath to my recolle(items 1 thru 3 of components, "/") --> "D1/D2/D3"
	set ppmName to my recolle(items 4 thru nbcomponents of components, "_") --> Nom du fichier d'origne
	
	# Create the destination subfolders if they aren't available
	set finalDest to create folder at (destinationDirectory & "/" & partialPath) --> "xxx/D1/D2/D3"
	# Move the file
	if forTests then
		copy object aFile to folder finalDest new name ppmName 
		#log result
		my writeto(reportPath, my horoDateur() & " - Ppm, ajout correct sur Prepstation:  " & ppmName & linefeed, «class utf8», true) # Write in the log file
		
	else
		move object aFile to folder finalDest new name ppmName 
		#log result
		my writeto(reportPath, my horoDateur() & " - Ppm, ajout correct sur Prepstation:  " & ppmName & linefeed, «class utf8», true) # Write in the log file
		
	end if
end repeat


#=====

on decoupe(t, d)
	local oTIDs, l
	set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
	set l to text items of t
	set AppleScript's text item delimiters to oTIDs
	return l
end decoupe

#=====

on recolle(l, d)
	local oTIDs, t
	set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
	set t to l as text
	set AppleScript's text item delimiters to oTIDs
	return t
end recolle

#=====

on writeto(targetFile, theData, dataType, apendData)
	-- targetFile is the path to the file you want to write
	-- theData is the data you want in the file.
	-- dataType is the data type of theData and it can be text, list, record etc.
	-- apendData is true to append theData to the end of the current contents of the file or false to overwrite it
	try
		set targetFile to targetFile as «class furl»
		set openFile to open for access targetFile with write permission
		--if not apendData then set eof of openFile to 0
		write theData to openFile starting at eof as dataType
		close access openFile
		return true
	on error
		try
			close access targetFile
		end try
		return false
	end try
end writeto

#=====

on horoDateur()
	set theFormatter to current application's NSDateFormatter's new()
	theFormatter's setDateFormat:"yyyy-MM-dd HH:mm:ss"
	return (theFormatter's stringFromDate:(current date)) as text
end horoDateur

#=====

To better understand the need here is an example of file name that both scripts must handle:

Macintosh HD/Users/dupont/Desktop/Entree/D1/D2/D3/pdfile-L001-100x100_120x120_D.pdf

The file name can have a variable length and several characters (“-” or “_”) placed in no particular order.

Thanks for your attention.

GK

For my scripts the structure of the file names doesn’t matter as long as it ends with “.pdf”

If I understand well you may use:

Script 1 to store the PDFs and possibly clear old folders

# Code Yvan/GK Script 1 --> Pdf vers Caldera

----------------------------------------------------------------
use AppleScript version "2.5"
use framework "Foundation"
use script "FileManagerLib" version "2.2.2"
use scripting additions
----------------------------------------------------------------
property forTests : true #  during tests I use copy object so the original files remain in place

# Working Folders
set sourceDirectory to POSIX path of "Macintosh HD:Users:dupont:Desktop:Entree:"
set logDirectory to POSIX path of "Macintosh HD:Users:dupont:Desktop:Logs:"
set destinationDirectory to POSIX path of "Macintosh HD:Users:dupont:Desktop:Caldera:"

# Date used to build the name of the log file / month
set theDate to current date
set time of theDate to 0 -- for future comparisons
set dateMinus45 to theDate - 45 * days -- for future comparisons
set reportPath to logDirectory & my monthStamp(theDate)

if not (exists object reportPath) then
	# Whe entered a new month,  creates a new logfile
	my writeto(reportPath, "", «class utf8», false)
end if

# Build a list of files embedded in sourceDirectory
set workingFiles to objects of sourceDirectory result type paths list with searching subfolders without include folders and include invisible items

repeat with aFile in workingFiles
	if aFile ends with ".pdf" then
		try
			# Extract the relevant components of the path of the file
			set components to my decoupe(aFile, "/")
			set {firstSubFolder, secondSubFolder, lateSubFolder} to items -4 thru -2 of components --> {"D1", "D2", "D3"} # ADDED
			set partialPath to my recolle({firstSubFolder, secondSubFolder}, "/") --> "D1/D2" # ADDED
			set newName to my recolle(items -4 thru -1 of components, "_") --> "D1_D2_D3_oldName.pdf"
			set dest1 to destinationDirectory & firstSubFolder # is a POSIX path
			set dest2 to dest1 & "/" & secondSubFolder # is a POSIX path
			set dest3 to dest2 & "/" & lateSubFolder # is a POSIX path
			--supprime les dossiers vieux de plus de 45 jours
			if (creation date of (info for POSIX file dest3)) < dateMinus45 then
				remove object dest3
				my writeto(reportPath, my horoDateur() & " - Dossier commande ancien supprime :  " & dest3 & linefeed, «class utf8», true)
			end if
			if (creation date of (info for POSIX file dest2)) < dateMinus45 then
				remove object dest2
				my writeto(reportPath, my horoDateur() & " - Dossier commande ancien supprime :  " & dest2 & linefeed, «class utf8», true)
			end if
			if (creation date of (info for POSIX file dest1)) < dateMinus45 then
				remove object dest1
				my writeto(reportPath, my horoDateur() & " - Dossier commande ancien supprime :  " & dest1 & linefeed, «class utf8», true)
			end if
			
			# Create the destination subfolders if they aren't available
			set finalDest to create folder at (destinationDirectory & "/" & partialPath) use name lateSubFolder --> "xxx/D1/D2/D3"
			# Move the file
			if forTests then
				copy object aFile to folder destinationDirectory new name newName
				#log result
				my writeto(reportPath, my horoDateur() & " - PDF, ajout correct sur RIP Caldera:  " & newName & linefeed, «class utf8», true) # append data to the log file
				
			else
				move object aFile to folder finalDest new name newName
				#log result
				my writeto(reportPath, my horoDateur() & " - PDF, ajout correct sur RIP Caldera:  " & newName & linefeed, «class utf8», true) # append data to the log file
			end if
		on error e number n
			my writeto(reportPath, my horoDateur() & " - Le fichier:  " & aFile & " n'a pas été traité, il est disponible" & linefeed, «class utf8», true) # append data to the log file
		end try
	end if
end repeat

#=====

on decoupe(t, d)
	local oTIDs, l
	set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
	set l to text items of t
	set AppleScript's text item delimiters to oTIDs
	return l
end decoupe

#=====

on recolle(l, d)
	local oTIDs, t
	set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
	set t to l as text
	set AppleScript's text item delimiters to oTIDs
	return t
end recolle

#=====

on writeto(targetFile, theData, dataType, apendData)
	-- targetFile is the path to the file you want to write
	-- theData is the data you want in the file.
	-- dataType is the data type of theData and it can be text, list, record etc.
	-- apendData is true to append theData to the end of the current contents of the file or false to overwrite it
	try
		set targetFile to targetFile as «class furl»
		set openFile to open for access targetFile with write permission
		if not apendData then set eof of openFile to 0
		write theData to openFile starting at eof as dataType
		close access openFile
		return true
	on error
		try
			close access targetFile
		end try
		return false
	end try
end writeto

#=====

on horoDateur()
	set theFormatter to current application's NSDateFormatter's new()
	theFormatter's setDateFormat:"yyyy-MM-dd HH:mm:ss"
	return (theFormatter's stringFromDate:(current date)) as text
end horoDateur

#=====

on monthStamp(aDate)
	set theFormatter to current application's NSDateFormatter's new()
	theFormatter's setDateFormat:"yyyy_MM"
	return ("Log_" & (theFormatter's stringFromDate:aDate)) & ".txt"
end monthStamp

#=====

Script 2 for the late task:

# Code Yvan/GK Script 2  --> Caldera-ppm vers Serveur

----------------------------------------------------------------
use AppleScript version "2.5"
use framework "Foundation"
use script "FileManagerLib" version "2.2.2"
use scripting additions
----------------------------------------------------------------
property forTests : true #  during tests I use copy object so the original files remain in place

# Working Folders	
set sourceDirectory to POSIX path of "Macintosh HD:Users:dupont:Desktop:CalderaPPM:"
set logDirectory to POSIX path of "Macintosh HD:Users:dupont:Desktop:Logs:"
set destinationDirectory to POSIX path of "images:0_PPM:" -- Folder on remote server -- local folder for test "Macintosh HD:Users:dupont:Desktop:0_PPM:" --

# Date used to build the name of the log file / month
set theDate to current date
set time of theDate to 0 -- for future comparisons
set dateMinus45 to theDate - 45 * days -- for future comparisons
set reportPath to logDirectory & my monthStamp(theDate)

# Build a list of files embedded in sourceDirectory
set workingFiles to objects of sourceDirectory result type paths list without searching subfolders and include invisible items --include folders and include invisible items

repeat with aFile in workingFiles
	try
		
		# Extract the relevant components of the path of the file
		set components to my decoupe(aFile, "/")
		set {firstSubFolder, secondSubFolder, lateSubFolder} to items -4 thru -2 of components --> {"D1", "D2", "D3"} # ADDED
		set partialPath to my recolle({firstSubFolder, secondSubFolder}, "/") --> "D1/D2" # ADDED
		set newName to my recolle(items -4 thru -1 of components, "_") --> "D1_D2_D3_oldName.ppm" -- ou ".pdf" if something failed before
		set dest1 to destinationDirectory & firstSubFolder # is a POSIX path
		set dest2 to dest1 & "/" & secondSubFolder # is a POSIX path
		set dest3 to dest2 & "/" & lateSubFolder # is a POSIX path
		--supprime les dossiers vieux de plus de 45 jours
		if (creation date of (info for POSIX file dest3)) < dateMinus45 then
			remove object dest3
			my writeto(reportPath, my horoDateur() & " - Dossier commande ancien supprime :  " & dest3 & linefeed, «class utf8», true)
		end if
		if (creation date of (info for POSIX file dest2)) < dateMinus45 then
			remove object dest2
			my writeto(reportPath, my horoDateur() & " - Dossier commande ancien supprime :  " & dest2 & linefeed, «class utf8», true)
		end if
		if (creation date of (info for POSIX file dest1)) < dateMinus45 then
			remove object dest1
			my writeto(reportPath, my horoDateur() & " - Dossier commande ancien supprime :  " & dest1 & linefeed, «class utf8», true)
		end if
		if aFile ends with ".ppm" then
			# Create the destination subfolders if they aren't available
			set finalDest to create folder at (destinationDirectory & "/" & partialPath) --> "xxx/D1/D2/D3"
			# Move the file
			if forTests then
				copy object aFile to folder finalDest new name ppmName
				#log result
				my writeto(reportPath, my horoDateur() & " - Ppm, ajout correct sur Prepstation:  " & ppmName & linefeed, «class utf8», true) # Write in the log file
				
			else
				move object aFile to folder finalDest new name ppmName
				#log result
				my writeto(reportPath, my horoDateur() & " - Ppm, ajout correct sur Prepstation:  " & ppmName & linefeed, «class utf8», true) # Write in the log file
				
			end if
		else
			# The document is not a ppm so it wasn't converted.
			error number 1943 # My birthYear is a good candidate for an error number
		end if
	on error e number n
		my writeto(reportPath, my horoDateur() & " - Erreur # " & n & " Le fichier " & aFile & " n'a pas été converti." & linefeed, «class utf8», true) # Write in the log file
	end try
end repeat

#=====

on decoupe(t, d)
	local oTIDs, l
	set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
	set l to text items of t
	set AppleScript's text item delimiters to oTIDs
	return l
end decoupe

#=====

on recolle(l, d)
	local oTIDs, t
	set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
	set t to l as text
	set AppleScript's text item delimiters to oTIDs
	return t
end recolle

#=====

on writeto(targetFile, theData, dataType, apendData)
	-- targetFile is the path to the file you want to write
	-- theData is the data you want in the file.
	-- dataType is the data type of theData and it can be text, list, record etc.
	-- apendData is true to append theData to the end of the current contents of the file or false to overwrite it
	try
		set targetFile to targetFile as «class furl»
		set openFile to open for access targetFile with write permission
		if not apendData then set eof of openFile to 0
		write theData to openFile starting at eof as dataType
		close access openFile
		return true
	on error
		try
			close access targetFile
		end try
		return false
	end try
end writeto

#=====

on horoDateur()
	set theFormatter to current application's NSDateFormatter's new()
	theFormatter's setDateFormat:"yyyy-MM-dd HH:mm:ss"
	return (theFormatter's stringFromDate:(current date)) as text
end horoDateur

#=====

on monthStamp(aDate)
	set theFormatter to current application's NSDateFormatter's new()
	theFormatter's setDateFormat:"yyyy_MM"
	return ("Log_" & (theFormatter's stringFromDate:aDate)) & ".txt"
end monthStamp

#=====

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) jeudi 8 aout 2019 18:34:48

Added code treating errors and delete old folders in script 2

Oops, I forgot to treat errors.
Message #24 is edited with new versions.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) vendredi 9 aout 2019 10:24:39

Thanks to Shane Stanley and Jonas Whale, here are alternate versions for one of my handlers.

on horoDateur() --> with milliseconds
	set theDate to current application's NSDate's |date|() # the 'complete' current date
	set theFormatter to current application's NSDateFormatter's new()
	theFormatter's setDateFormat:"yyyy-MM-dd AAAAAAAA"
	return (theFormatter's stringFromDate:theDate) as text --> (*2019-08-09 00551161*)
end horoDateur

It doesn’t return the time as hh:mm:ss but as the count of milliseconds in the day.
It’s more precise than the use of current date which count the seconds, not the milliseconds

on horoDateur() --> without milliseconds
	set theFormatter to current application's NSDateFormatter's new()
	theFormatter's setDateFormat:"yyyy-MM-dd AAAAAAAA"
	return text 1 thru -4 of ((theFormatter's stringFromDate:(current date)) as text) --> (*2019-08-09 00551*)
end horoDateur

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) vendredi 9 aout 2019 15:40:15

I’m an ass.

I just discovered that the script 0 supposed to create a new logfile was not required. Look at message #24 to get new scripts.

A problem bothers me.
I’m afraid that the removing of old folders doesn’t work correctly.
Assuming that D1 was created on 2019/07/01, D2-1 and D3-1-1 ditto
D2-2 was created on 2019/07/15
D3-2-1 was created on 2019/07/15 in D2/2
If we try to write a new file in D1/D2-1/D3-1-1 on 2019/09/03,
D3-1-1 will be removed which is OK
D2-1 will be removed which is OK
D1 will be removed too and it’s bad.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) samedi 10 aout 2019 09:16:24

I assume that replacing (in both scripts) :

if (creation date of (info for POSIX file dest3)) < dateMinus45 then
	remove object dest3
	my writeto(reportPath, my horoDateur() & " - Dossier commande ancien supprime :  " & dest3 & linefeed, «class utf8», true)
end if
if (creation date of (info for POSIX file dest2)) < dateMinus45 then
	remove object dest2
	my writeto(reportPath, my horoDateur() & " - Dossier commande ancien supprime :  " & dest2 & linefeed, «class utf8», true)
end if
if (creation date of (info for POSIX file dest1)) < dateMinus45 then
	remove object dest1
	my writeto(reportPath, my horoDateur() & " - Dossier commande ancien supprime :  " & dest1 & linefeed, «class utf8», true)
end if

by

if (creation date of (info for POSIX file dest3)) < dateMinus45 then
	remove object dest3
	my writeto(reportPath, my horoDateur() & " - Dossier commande ancien supprime :  " & dest3 & linefeed, «class utf8», true)
end if
if ((creation date of (info for POSIX file dest2)) < dateMinus45) and (objects of dest2 with include folders without searching subfolders and include invisible items) = {} then
	remove object dest2
	my writeto(reportPath, my horoDateur() & " - Dossier commande ancien supprime :  " & dest2 & linefeed, «class utf8», true)
end if
if ((creation date of (info for POSIX file dest1)) < dateMinus45) and (objects of dest1 with include folders without searching subfolders and include invisible items) = {} then
	remove object dest1
	my writeto(reportPath, my horoDateur() & " - Dossier commande ancien supprime :  " & dest1 & linefeed, «class utf8», true)
end if

would be better.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) samedi 10 aout 2019 14:13:30

Hello,

Yvan thank you again for all your work.
I think that for removing old folder we could rather check the file modification date rather than the creation date. in our use, the files are used between 1 week and a month. That’s why I chose 45 days.

I will try your new code and come back to show here.

GK

At : http://www.hamsoftengineering.com/codeSharing/ChangeFileDates/ChangeFileDates.html
I found a CLI allowing me to change the creation dates of items.
Thanks to it I was able to create a folder with old items.
This let me discover that some instructions were wrongly formed.
Here is the correct block of instructions:

--supprime les dossiers vieux de plus de 45 jours
set maybe to POSIX file dest3 # ADDED
if (creation date of (info for maybe)) < dateMinus45 then # EDITED
	remove object dest3 with folders included # EDITED
	my writeto(reportPath, my horoDateur() & " - Dossier commande ancien supprime :  " & dest3 & linefeed, «class utf8», true)
end if
set maybe to POSIX file dest2 # ADDED
if ((creation date of (info for maybe)) < dateMinus45) and (objects of dest2 with include folders without searching subfolders and include invisible items) = {} then # EDITED
	remove object dest2 with folders included # EDITED
	my writeto(reportPath, my horoDateur() & " - Dossier commande ancien supprime :  " & dest2 & linefeed, «class utf8», true)
end if
set maybe to POSIX file dest1 # ADDED
if ((creation date of (info for maybe)) < dateMinus45) and (objects of dest1 with include folders without searching subfolders and include invisible items) = {} then # EDITED
	remove object dest1 with folders included # EDITED
	my writeto(reportPath, my horoDateur() & " - Dossier commande ancien supprime :  " & dest1 & linefeed, «class utf8», true)
end if


I understand what was wrong with the instruction remove object which was treating only files, not folders.
I’m puzzled by the behavior of info for.

creation date of (info for (POSIX file dest3)) issued an error.

set maybe to POSIX file dest3
creation date of (info for maybe)
work flawlessly

I dislike such case where I don’t understand what is wrong but at least, I have a working code.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) dimanche 11 aout 2019 11:58:49

Hi Yvan.

There’s a trick which still seems to work if you want to make a file look as if it was created before it really was — and that is to set its modification date to the earlier date. The creation date goes back to match this. You can then put the modification date forward again if you want. :slight_smile:

Assuming that dest3’s a valid POSIX path, it works for me. :confused:

It works in a bare demo script but failed in the complete one.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) dimanche 11 aout 2019 14:39:13

Or you can do it this way:

set theURL to current application's NSURL's fileURLWithPath:posixPath
theURL's setResourceValue:(current date) forKey:(current application's NSURLCreationDateKey) |error|:(missing value)

And your file was created after it was last modified :cool:

Bingo.
At last, the pig headed guy found what was wrong.

creation date of (info for (POSIX file aPath))

works in a ‘standard’ script but fails in a script using an instruction use framework “aFramework”.
In this late case, we must use creation date of (info for ( aPath as «class furl»))

I tested with this bare script:

----------------------------------------------------------------
use AppleScript version "2.5"
use framework "Foundation"
use script "FileManagerLib" version "2.2.2"
use scripting additions
----------------------------------------------------------------
script o # ADDED
	property reportPath : "" # ADDED
	property dateMinus45 : missing value # ADDED
end script # ADDED

set p2d to path to desktop as text
set sourceDirectory to POSIX path of (p2d & "D1 kopy:")
set logDirectory to POSIX path of p2d
set destinationDirectory to POSIX path of (p2d & "dest:")

# Date used to build the name of the log file / month
set theDate to current date
set time of theDate to 0 -- for future comparisons
set o's dateMinus45 to theDate - 45 * days -- EDITED with o's
set theFormatter to current application's NSDateFormatter's new()
theFormatter's setDateFormat:"yyyy_MM"
set o's reportPath to logDirectory & ("Log_" & (theFormatter's stringFromDate:theDate)) & ".txt" # EDITED with o's

if not (exists object o's reportPath) then # EDITED with o's
	# Whe entered a new month,  creates a new logfile
	my writeto(o's reportPath, "", «class utf8», false) # EDITED with o's
end if

set aFile to POSIX path of (p2d & "D1 kopie:D2-2:D2-2-2:Ticket.pdf")

# Extract the relevant components of the path of the file
set components to my decoupe(aFile, "/")
set {firstSubFolder, secondSubFolder, lateSubFolder} to items -4 thru -2 of components --> {"D1", "D2", "D3"}
set partialPath to my recolle({firstSubFolder, secondSubFolder}, "/") --> "D1/D2"
set newName to my recolle(items -4 thru -1 of components, "_") --> "D1_D2_D3_oldName.pdf"
set dest1 to destinationDirectory & firstSubFolder # is a POSIX path
set dest2 to dest1 & "/" & secondSubFolder # is a POSIX path
set dest3 to dest2 & "/" & lateSubFolder # is a POSIX path

-- Remove the files more than 45 days old
my CleanFolder(dest3)
my CleanFolder(dest2)
my CleanFolder(dest1)

#=====

on CleanFolder(dest)
	set existingFiles to objects of dest result type paths list without searching subfolders, include folders and include invisible items
	repeat with aPath in existingFiles
		if (creation date of (info for (aPath as «class furl»))) < o's dateMinus45 then # EDITED with o's
			remove object aPath # OK for file, wrong for folder
			my writeto(o's reportPath, my horoDateur() & " - Fichier commande ancien supprimé :  " & aPath & linefeed, «class utf8», true) # EDITED with o's
		end if
	end repeat
end CleanFolder

#=====

on decoupe(t, d)
	local oTIDs, l
	set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
	set l to text items of t
	set AppleScript's text item delimiters to oTIDs
	return l
end decoupe

#=====

on recolle(l, d)
	local oTIDs, t
	set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
	set t to l as text
	set AppleScript's text item delimiters to oTIDs
	return t
end recolle

#=====

on writeto(targetFile, theData, dataType, apendData)
	-- targetFile is the path to the file you want to write
	-- theData is the data you want in the file.
	-- dataType is the data type of theData and it can be text, list, record etc.
	-- apendData is true to append theData to the end of the current contents of the file or false to overwrite it
	try
		set targetFile to targetFile as «class furl»
		set openFile to open for access targetFile with write permission
		--if not apendData then set eof of openFile to 0
		write theData to openFile starting at eof as dataType
		close access openFile
		return true
	on error
		try
			close access targetFile
		end try
		return false
	end try
end writeto

#=====

on horoDateur()
	set theFormatter to current application's NSDateFormatter's new()
	theFormatter's setDateFormat:"yyyy-MM-dd HH:mm:ss"
	return (theFormatter's stringFromDate:(current date)) as text
end horoDateur

#=====


The script’s history displayed:

tell current application
	path to desktop as text
		--> "SSD 500:Users:**********:Desktop:"
	current date
		--> date "dimanche 11 août 2019 à  15:10:57"
	(*/Users/**********/Desktop/dest/D1 kopie/D2-2/D2-2-2/Ticket.pdf*)
	info for file "SSD 500:Users:**********:Desktop:dest:D1 kopie:D2-2:D2-2-2:Ticket.pdf"
		--> {name:"Ticket.pdf", creation date:date "samedi 1 juin 2019 à  00:01:02", modification date:date "samedi 1 juin 2019 à  01:02:03", size:46290, folder:false, alias:false, package folder:false, visible:true, extension hidden:false, name extension:"pdf", displayed name:"Ticket.pdf", default application:alias "SSD 500:Applications:Preview.app:", kind:"Document PDF", file type:", file creator:", type identifier:"com.adobe.pdf", locked:false, busy status:false, short version:"", long version:""}
	current date
		--> date "dimanche 11 août 2019 à  15:10:57"
	open for access file "SSD 500:Users:**********:Desktop:Log_2019_08.txt" with write permission
		--> 719
	write "2019-08-11 15:10:57 - Fichier commande ancien supprimé :  /Users/**********/Desktop/dest/D1 kopie/D2-2/D2-2-2/Ticket.pdf
" to 719 starting at eof as «class utf8»
	close access 719
end tell

So, in the main scripts we must add the new handler on CleanFolder(dest, dateMinus45, reportPath)
the script object
script o # ADDED
property reportPath : “” # ADDED
property dateMinus45 : missing value # ADDED
end script # ADDED

edit the instructions commented by # EDITED withn o’s
and replace the old group of instructions by:

# Extract the relevant components of the path of the file
set components to my decoupe(aFile, "/")

set {firstSubFolder, secondSubFolder, lateSubFolder} to items -4 thru -2 of components --> {"D1", "D2", "D3"} # ADDED
set partialPath to my recolle({firstSubFolder, secondSubFolder}, "/") --> "D1/D2" # ADDED
set newName to my recolle(items -4 thru -1 of components, "_") --> "D1_D2_D3_oldName.pdf"
set dest1 to destinationDirectory & firstSubFolder # is a POSIX path
set dest2 to dest1 & "/" & secondSubFolder # is a POSIX path
set dest3 to dest2 & "/" & lateSubFolder # is a POSIX path

--supprime les fichiers vieux de plus de 45 jours
my CleanFolder(dest3)
my CleanFolder(dest2)
my CleanFolder(dest1

If like me you dislike the use of the deprecated info for
you may replace the handler by:

on CleanFolder(dest)
	set existingFiles to objects of dest result type paths list without searching subfolders, include folders and include invisible items
	repeat with aPath in existingFiles
		set theURL to (current application's NSURL's fileURLWithPath:aPath)
		set {theResult, NSDate, theError} to (theURL's getResourceValue:(reference) forKey:(current application's NSURLCreationDateKey) |error|:(reference))
		if (NSDate as date) < o's dateMinus45 then # EDITED with o's
			remove object aPath # OK for file, wrong for folder
			my writeto(o's reportPath, my horoDateur() & " - Fichier commande ancien supprimé :  " & aPath & linefeed, «class utf8», true) # EDITED with o's
		end if
	end repeat
end CleanFolder

which just requires more typing.

Yvan KOENIG running High Sierra 10.13.6 in French (VALLAURIS, France) dimanche 11 aout 2019 15:45:31