Skip to content

Instantly share code, notes, and snippets.

@3panda
Created February 7, 2021 02:08
Show Gist options
  • Save 3panda/771a76fe8b73b255e541b91439dbe351 to your computer and use it in GitHub Desktop.
Save 3panda/771a76fe8b73b255e541b91439dbe351 to your computer and use it in GitHub Desktop.
指定したフォルダのURLからファイル名とURLを取得して一覧にするGAS

以下のような親と子が複数いる状況で、スプレットシートのシート別に引っ張ってくるものが違ったりする場合を想定 (メモ書きなので詳細な解説はしません)

親
|-子1
|-子2
|-子3
function getFileInformation() {
  //アクティブなシートを取得
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var activeSheet = spreadsheet.getActiveSheet();
  var activeSheetName = activeSheet.getName();
  console.log(activeSheetName);

 //対象のディレクトリのURLを取得
  var targetDirectoryURL = activeSheet.getRange('C1').getValue();
  console.log(targetDirectoryURL);

 //対象の子ディレクトリの名前を取得
  var targetSubDirectoryName = activeSheet.getRange('C2').getValue();
  console.log(targetSubDirectoryName);

  //idを取得
  var myArray = targetDirectoryURL.split(`/`);
  console.log(myArray);
  var folderid = myArray[myArray.length-1];
  console.log(folderid);

  // 子フォルダ
  var folders = DriveApp.getFolderById(folderid).getFolders();
  var myFolderName = [];
  var myFolderId = [];

  while (folders.hasNext()) {
    var folder = folders.next();
    var folderName = folder.getName();
    Logger.log(folderName);
    myFolderName.push(folder.getName())
    myFolderId.push(folder.getId())
    
    }
  console.log(myFolderName);
  console.log(myFolderId);
  
  var targetFolderId;

  for (var step = 0; step < myFolderName.length; step++) {
    if(myFolderName[step] == targetSubDirectoryName){
      targetFolderId = myFolderId[step];
      console.log(targetFolderId);
      break;
    }
    
  }

  console.log(targetFolderId);

    //調査したいフォルダ内のファイルを取得
  var targetFolder = DriveApp.getFolderById(targetFolderId); 
  var targetfiles = targetFolder.getFiles();
  var targetDirectoryName = targetFolder.getName();
  console.log(targetDirectoryName);
  //ファイルとフォルダの情報を入れる配列
  var myTargeterFolder = [];

  //ファイル名とファイルURLをmyTargeterFolderに格納
  while(targetfiles.hasNext()){
    var file = targetfiles.next();
    myTargeterFolder.push([file.getName(),file.getUrl()])
  }
  
  console.log(myTargeterFolder);
 

  // シートに情報を貼り付ける
  // 対処のファルダーのURL
  var TargeterFolderURL = DriveApp.getFolderById(targetFolderId).getUrl();
  activeSheet.getRange(4, 3).setValue(TargeterFolderURL);
  console.log(TargeterFolderURL);
  // ファイル名とURL
  activeSheet.getRange(6, 2, myTargeterFolder.length, myTargeterFolder[0].length).setValues(myTargeterFolder);

  console.log(myTargeterFolder.length);
  console.log(myTargeterFolder[0].length);
  // 選択したセルで降順に並び替え
  var data = activeSheet.getRange(6, 2, myTargeterFolder.length, myTargeterFolder[0].length);
  data.sort({column: 2, ascending: true});
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment