Google Apps Script文件复制函数问题:按描述匹配复制文件至对应文件夹
Fix: Copying Files to Matching Subfolders in Google Apps Script
Let's break down what's wrong with your current code and fix it step by step. The core issue is how you're iterating over the subfolders—your second loop has incorrect syntax and logic that stops you from checking all possible folders.
What Was Broken in Your Original Code
- You only grabbed the first subfolder with
var folders = folderIter.next()and then tried to use a broken while loop to "skip" non-matching folders. The linefolderIter.hasNext().next()is invalid becausehasNext()returns a boolean, not the iterator itself. - You never properly looped through all subfolders to find the one whose description matches the file's.
Corrected Code
function CopySheetsIntoGoodFolder2() { // Get the source folder containing files to copy const sourceFolder = DriveApp.getFolderById('123C'); // Get the parent folder holding your dynamically created subfolders const targetParentFolder = DriveApp.getFolderById('123D'); // Iterate over every file in the source folder const filesIter = sourceFolder.getFiles(); while (filesIter.hasNext()) { const currentFile = filesIter.next(); const fileDescription = currentFile.getDescription(); // Iterate over every subfolder in the target parent folder const subfoldersIter = targetParentFolder.getFolders(); let foundMatchingFolder = false; while (subfoldersIter.hasNext()) { const currentSubfolder = subfoldersIter.next(); const folderDescription = currentSubfolder.getDescription(); // Check if file and folder descriptions match if (fileDescription === folderDescription) { // Copy the file to the matching subfolder currentFile.makeCopy(currentSubfolder); foundMatchingFolder = true; // Uncomment this line if you only need to copy to the first matching folder // break; } } // Optional: Log when no matching folder exists for a file (great for debugging) if (!foundMatchingFolder) { console.log(`No matching folder found for file: ${currentFile.getName()} (description: ${fileDescription})`); } } }
Key Improvements
- Clearer variable names: Renamed variables like
folderFilestosourceFolderto make the code easier to follow. - Proper subfolder iteration: We use a full
while (subfoldersIter.hasNext())loop to check every subfolder in the target parent folder. - Valid iterator usage: Each time we call
subfoldersIter.next(), we get the next subfolder and compare its description to the file's. - Debugging support: Added a
foundMatchingFolderflag to log cases where no matching folder exists for a file. - Flexibility: If you only need to copy a file to the first matching folder, uncomment the
break;line. If you want to copy to all matching folders, leave it out.
This code will correctly loop through all files, then loop through all subfolders for each file, and copy the file to any subfolder where the descriptions match.
内容的提问来源于stack exchange,提问作者Nalec
相关产品推荐
相关产品推荐

