GAS Drive 管理雲端硬碟檔案

透過 DriveApp 服務,你可以用程式碼自動化管理 Google 雲端硬碟。無論是建立資料夾、動態產生檔案,還是批次修改權限,都能輕鬆達成。

基本檔案與資料夾操作

GAS 可以幫你整理凌亂的雲端硬碟,自動歸檔檔案。

/**
 * 建立資料夾並在其中產生一個新檔案
 */
function createFolderAndFile() {
  // 建立資料夾
  const folder = DriveApp.createFolder('專案備份_2024');
  
  // 在該資料夾建立一個文字檔
  const file = folder.createFile('README.txt', '這是自動產生的說明文件。');
  
  console.log(`檔案已建立,ID 為: ${file.getId()}`);
}

基礎操作函數語法說明

  • DriveApp.createFolder(name):在根目錄建立一個新資料夾。
  • folder.createFile(name, content):在指定資料夾中建立新檔案(預設為文字檔)。
  • file.getId():取得檔案或資料夾的唯一識別碼 (ID),這是後續操作的重要依據。
  • DriveApp.getFileById(id) / DriveApp.getFolderById(id):直接透過 ID 取得檔案或資料夾物件。

搜尋與過濾檔案

當檔案非常多時,你需要使用 searchFilessearchFolders 配合特殊的查詢語法。

/**
 * 搜尋所有名稱包含「發票」且在 2024 年之後修改的 PDF 檔案
 */
function searchSpecificFiles() {
  const query = "title contains '發票' and mimeType = 'application/pdf' and modifiedDate > '2024-01-01'";
  const files = DriveApp.searchFiles(query);
  
  while (files.hasNext()) {
    const file = files.next();
    console.log(`找到檔案: ${file.getName()} (ID: ${file.getId()})`);
  }
}

搜尋相關函數語法說明

  • searchFiles(params):使用特定的搜尋語法(類似 SQL 但不同)來過濾檔案。
  • hasNext():檢查迭代器(Iterator)中是否還有下一個檔案。
  • next():取出下一個檔案物件。
  • mimeType:常見格式如 'application/pdf', 'image/jpeg', 'application/vnd.google-apps.spreadsheet' (試算表)。

權限管理與共用

GAS 能讓你動態地加入或移除檔案的協作者。

/**
 * 將特定檔案分享給合作夥伴,並設定為「僅限檢視」
 */
function updatePermissions() {
  const file = DriveApp.getFileById('YOUR_FILE_ID');
  
  // 加入檢視者
  file.addViewer('partner@example.com');
  
  // 加入編輯者
  file.addEditor('manager@example.com');
  
  // 移除特定人員
  file.removeEditor('old_member@example.com');
  
  // 設定公眾連結存取 (任何人具備連結皆可編輯)
  file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.EDIT);
}

權限相關函數語法說明

  • addEditor(email) / addViewer(email):透過 Email 加入編輯者或檢視者。
  • setSharing(access, permission):設定檔案的共享層級。
    • AccessPRIVATE (私用), ANYONE (任何人), ANYONE_WITH_LINK (具連結者)。
    • PermissionVIEW (檢視), EDIT (編輯), COMMENT (評論)。

批次管理與資源回收桶

/**
 * 將特定資料夾內的所有檔案移至回收桶
 */
function cleanupFolder() {
  const folder = DriveApp.getFolderById('YOUR_FOLDER_ID');
  const files = folder.getFiles();
  
  while (files.hasNext()) {
    const file = files.next();
    file.setTrashed(true); // 移至回收桶
  }
}

批次操作函數語法說明

  • folder.getFiles() / folder.getFolders():取得該資料夾下「所有」的檔案或子資料夾。
  • setTrashed(boolean):設定檔案是否進入回收桶。
  • file.makeCopy(name, destination):複製檔案到指定的資料夾。