Search file based on filename and attach link

Hi, I would like to make a script that search a folder and its subfolder to find a file, based on the filename, that is stored in a specific field of the records (in my case, in the Short title field). When it finds the file, the script attach into the record a link to the file.
I've asked AI to make this script and it returned the following, but it does not work. Someone could help me? Thanks, luca

const { FileUtils } = Components.utils.import("resource://gre/modules/FileUtils.jsm");

(async () => {
const baseFolderPath = "/media/myFolder"; // Update this to your actual folder path

// Use the items passed to the script
const targetItems = items || (item ? [item] : []);

for (let item of targetItems) {
if (!item.isRegularItem()) continue; // Skip non-regular items
if (item.getAttachments().length > 0) continue; // Skip items that already have attachments

const shortTitle = item.getField('shortTitle'); // Get the short title
if (!shortTitle) continue; // Skip if there's no short title

try {
// Call the recursive search function
const filePath = await findFileRecursive(baseFolderPath, shortTitle);
if (filePath) {
await item.linkAttachmentFile(filePath); // Link the found file to the item
Zotero.debug(`Linked file ${filePath} to record ${item.id}`);
} else {
Zotero.debug(`No matching file found for ${shortTitle}`);
}
} catch (e) {
Zotero.debug(`Error searching or linking file for ${shortTitle}: ${e}`);
}
}
})();

// Recursively searches for a file with the given filename in the specified folder and subfolders
async function findFileRecursive(folderPath, filename) {
const folder = new FileUtils.File(folderPath);
const dirEntries = folder.directoryEntries;

while (dirEntries.hasMoreElements()) {
const entry = dirEntries.getNext().QueryInterface(Components.interfaces.nsIFile);
if (entry.isDirectory()) {
const result = await findFileRecursive(entry.path, filename);
if (result) return result; // Return the found file path if found in subdirectory
} else if (entry.isFile() && entry.leafName === filename) {
return entry.path; // Return the path of the matching file
}
}

return null; // Return null if no matching file is found
}
Sign In or Register to comment.