How do I locate the path of the folder in which the current script file is located?

后端 未结 5 898
小鲜肉
小鲜肉 2020-12-21 09:46

How do I locate the path of the current folder? I just want to be able to get the path of the folder so that I can manipulate the files in the folder without typing the path

5条回答
  •  情歌与酒
    2020-12-21 10:21

    I was able to get the folder containing the script that was running:

    //
    // PrintScriptFolder -- print the name of the folder in which the running script resides.
    //
    function PrintScriptFolder()
    {
      var scriptId = ScriptApp.getScriptId();
      console.info('scriptId = ' + scriptId);
      
      var file = DriveApp.getFileById(scriptId);
      var folders = file.getParents();
      if (folders.hasNext())
      {
        var folder = folders.next();
        var name = folder.getName();
        console.info('script folder name = ' + name);    
      }  
    }
    

    The trick is using ScriptApp to get the ID of the running script. From there it's pretty straightforward: use DriveApp to get the file ID, getParents() to get a list of (one) parent folder, next() to get it, and getName() to get its name.

提交回复
热议问题