[Extendscript] Best way to move a file via script.
Hi Scripters, does anyone know of the best way to move files via script? For example, here is one method that I got to work, but it has the bad side effect of destroying the file's created/modified dates because it duplicates the file into the desired location, then removes the original. I'm looking for something that works in Illustrator and is cross-platform. Any help would be much appreciated.
- Mark
(function () {
// WARNING: do not run with an
// important document open!
// Example: takes the active document
// and moves it into a "test" folder
// created in its current folder
var doc = app.activeDocument,
docFile = doc.fullName,
folder = Folder(docFile.parent.absoluteURI + '/test');
doc.close(SaveOptions.DONOTSAVECHANGES);
var movedDocFile = moveFileByCopyDelete(docFile, folder);
app.open(movedDocFile);
})();
/**
* Copies a file to a given folder,
* and removes the original, returning
* a new reference to the copy.
* Notes:
* - This function is a poor workaround
* for the lack of a proper MOVE command.
* - You will lose file metadata such as
* created/modified dates.
* - The original `file` reference will be
* invalid after the move, but you can
* update it using the returned file.
* @7111211 m1b
* @version 2023-08-20
* @9397041 {File} file - the file to move.
* @9397041 {Folder} folder - the destination folder.
* @Returns {File} the moved file.
*/
function moveFileByCopyDelete(file, folder) {
if (!file || !folder)
return;
if (file.constructor.name == 'String')
file = File(file);
if (folder.constructor.name == 'String')
folder = Folder(folder);
if (!folder.exists)
folder.create();
if (!file.exists || !folder.exists)
return;
var fileCopy = File(folder.absoluteURI + '/' + file.name);
file.copy(fileCopy);
if (fileCopy.exists)
file.remove();
return fileCopy;
};
