In Google Apps Script, how would I get all subfold

2020-05-01 06:32发布

问题:

I am attempting to rename every file in a specified folder and all files in all subfolders but I cannot figure out how to do so. I so far have this script that renames every file in a folder given its Id, but I need to do all subfolders.

function renameFilesInFolder(folderID) {
  var folder = DriveApp.getFolderById(folderID)
  var files = folder.getFiles(),
      fileNames = []
  

  while(files.hasNext()){
    var file = files.next()
    var oldFileName = file.getName()
    var checkIfMatch = oldFileName.substring(oldFileName.length - 3);
    var newFileName = ""
    if (checkIfMatch=="OBS"){
      newFileName = oldFileName
    } else {
      newFileName =oldFileName+"_OBS"
    }
    file.setName(newFileName)
    Logger.log(newFileName)
  }
}
Thank you!

回答1:

This will recurse through the folder writing them into a spreadsheet.

var level=0;
function getFnF(folder) {
  var folder= folder || DriveApp.getRootFolder();
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName('FilesAndFolders')
  var files=folder.getFiles();
  while(files.hasNext()) {
    var file=files.next();
    var firg=sh.getRange(sh.getLastRow() + 1,level + 1);
    firg.setValue(Utilities.formatString('File: %s', file.getName()));
  }
  var subfolders=folder.getFolders() 
  while(subfolders.hasNext()) {
    var subfolder=subfolders.next();
    var forg=sh.getRange(sh.getLastRow() + 1,level + 1);
    forg.setValue(Utilities.formatString('Fldr: %s', subfolder.getName()));
    level++;
    getFNF(subfolder);
  }
  level--;
}