Search code examples
google-apps-scriptgoogle-drive-apigoogle-sheets-apigoogle-drive-shared-drive

Google Apps Script: moveTo function throws exception for some users when a file is moved to a shared drive folder


In gSheets, I wrote an apps script which creates a DocX file based on a gDoc. The DocX file is then moved to the target folder, which is a shared gDrive folder.

Here's the code snippet:

function createDocX(docID, rowData, subFolder) {
var token = ScriptApp.getOAuthToken();
var blb = UrlFetchApp.fetch('https://docs.google.com/feeds/download/documents/export/Export?id='+docID+'&exportFormat=docx', 
                          {headers : {Authorization : 'Bearer '+ token}}).getBlob();
//Create the docx file in Google Drive
var docxFile = DriveApp.createFile(blb).setName(`${rowData[0][3]}_Report.docx`);
//Move the docx file
docxFile.moveTo(subFolder);
}

Here is how I created the destination folder:

var subFolder = folder.createFolder(rowData[0][3]);

I used the same script on another spreadsheet and it worked fine for every user in my team. However, I made a new spreadsheet and the script runs just for me and one other early adopter of the script. When a new user tries to use the script, they get the following error:

Exception: Unexpected error while getting the method or property moveTo on object DriveApp.File.

I checked that every user has access to the shared folder where the file should be moved to.

EDIT: It seems like the issue is caused by the shared drive. If I change the destination folder to the original one, it does work for everyone. However, it does not work for a new folder in the exact same directory.


Solution

  • Assuming that all users running the script have the correct access to subFolder, you can directly create the file there instead of moving it

    Modify

    var docxFile = DriveApp.createFile(blb).setName(`${rowData[0][3]}_Report.docx`);
    //Move the docx file
    docxFile.moveTo(subFolder)
    

    to

    var docxFile = DriveApp.getFolderById('here goes folder id as string').createFile(blb).setName(`${rowData[0][3]}_Report.docx`);
    

    If the modified code snippet does not work for you, check the following:

    • The users running the code need to have the role "Contributor" or "Content Manager" for the folder on the shared Drive
    • Make sure that the code is running on behalf othe suer(s) with the respective permissions and not on behalf of a different user (can happen if the function run's triggered by an installable trigger or executed as a webApp.)
    • Log the subFolder id within the funciton to make sure the correct folder is addressed