You basically need two functions but you only need to run one of them; that is the main function.
Explanation:
Function fileMover will take care of the moving of the files:
function fileMover(id,targetFolderId,parentFolderId) {
const file = DriveApp.getFileById(id)
file.getParents().next().removeFile(file);
try {
DriveApp.getFolderById(targetFolderId).addFile(file);}
catch(e){
const parentFolder=DriveApp.getFolderById(parentFolderId);
const newFolder=parentFolder.createFolder(file.getName() + " folder");
DriveApp.getFolderById(newFolder.getId()).addFile(file);
}
}
And the function main will iterate through the columns and execute fileMover for every row in your file:
function main () {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1');
const parentFolderId = 'parentfoldeidhere';
const file_ids = sh.getRange("A2:A"+sh.getLastRow()).getValues().flat([1]);
const folder_ids = sh.getRange("B2:B"+sh.getLastRow()).getValues().flat([1]);
for (var i = 0 ; i < file_ids.length ; i++){
fileMover(file_ids[i],folder_ids[i],parentFolderId)
}
}
Important information:
As you can see in the main function, there is a variable parentFolderId. This folder is used as a placeholder for all the new folders that are being created when Column B (Folder_ID) does not provide a correct id. This is a better practice to keep your files organized within one "parent" folder.
Here is the structure of my spreadsheet file. Column A provides a list of the IDs of the files you want to move. And Column B provides a list of the folder IDs that you want to move the files in the same rows. If Column B provides a wrong folder ID, then a new folder will be created in the parent folder (adjust parent folder id in the main function). The new folder will have the name: nameofthefile + " folder"
, but this can also be adjusted in line: file.getName() + " folder"
of the fileMover
function. Also, feel free to adjust the name of the sheet, in my case Sheet1.
