1
votes

In Google Sheets i have 2 columns: A)"Google Drive file IDs" B)"New File Paths".

I like a script that could move the file to the path according to the path in the cell. And could create the folder if the folder doesn't exist.

I found this script "Move File to a Different Folder in Google Drive" but would need help getting it to work in Sheets

1
what do you mean by New File Paths ? would that be a folder id for example?soMario
Great idea! yes, i could use a Folder ID insteadWeW
Awesome Thank youWeW

1 Answers

2
votes

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.

example