Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

In Google Apps Script, how would I get all subfolders and all subsubfolders and all subsubsub folders etc.?

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)
  }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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--;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...