概要
Google Apps Scriptで、操作をしているファイルのあるフォルダ(カレントフォルダ)を取得したい場合があると思います。
その時に使用するメソッドの紹介と使い方です。
使用するメソッド
構文
Fileオブジェクト.getParents()
引数
なし
戻り値
FolderIterator(Folderのコレクション)
サンプルプログラム
親フォルダが1つの場合
function sample() {
// ファイルID
const FILE_ID = PropertiesService.getScriptProperties().getProperty("FILE_ID");
// ファイルを取得
const file = DriveApp.getFileById(FILE_ID);
// カレントフォルダの取得
const currentFolder = file.getParents().next();
// コンソールにカレントフォルダ名を出力
console.log(currentFolder.getName());
}
親フォルダが複数の場合
function sample() {
// ファイルID
const FILE_ID = PropertiesService.getScriptProperties().getProperty("FILE_ID");
// ファイルを取得
const file = DriveApp.getFileById(FILE_ID);
// カレントフォルダの取得
const currentFolders = file.getParents();
// カレントフォルダの件数分繰り返し
while (currentFolders.hasNext()) {
// カレントフォルダの取得
let currentFolder = currentFolders.next();
// コンソールにカレントフォルダ名を出力
console.log(currentFolder.getName());
}
}