LoginSignup
0
0

More than 3 years have passed since last update.

GASを使ってGoogleDrive内のデータを定期的にバックアップする

Last updated at Posted at 2020-06-07

はじめに

GoogleDriveの特定フォルダ内のデータを定期的にバックアップ(別フォルダにコピーを作成)したかったので、自動化してみました

コード

sample.js
/**
 * メイン処理
 */
function main() {
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = spreadsheet.getActiveSheet();
  const copyBaseDirectoryID = sheet.getRange("B1").getValue();
  const copyTargetParentDirectoryID = sheet.getRange("B2").getValue();
  const outputParentDirectory = DriveApp.getFolderById(copyTargetParentDirectoryID);
  const inputDirectory = DriveApp.getFolderById(copyBaseDirectoryID)

  //現在日時を取得
  const now = new Date();

  //取得した現在日時を指定した表示形式に変換
  const time = Utilities.formatDate(now, "Asia/Tokyo", "yyyy_MM_dd_HH_mm_ss");

  // コピー先となるディレクトリを作成
  const outputDirectory = outputParentDirectory.createFolder(time);

  //フォルダ内のファイルを一括取得
  const files = inputDirectory.getFiles();

  // 指定箇所にファイルをコピー  
  for(let i = 0; files.hasNext(); i++) {
    const file = files.next();
    const baseData = DriveApp.getFileById(file.getId());

    baseData.makeCopy(file.getName(), outputDirectory);
  }
}

/**
 * カスタムメニュー
 */
function onOpen()
{
    const ui = SpreadsheetApp.getUi();
    ui.createMenu("マクロ")
        .addItem("ディレクトリのコピーを実行", "main")
        .addToUi();
}

デモ

※閲覧できない場合はGoogleアカウントを一度ログアウトしてからお試し下さい
https://docs.google.com/spreadsheets/d/1NqdvyWAsJrqlW0bGN2u_YnO7EixlSVnmvZ4G4AhJQ70/edit#gid=0

フォルダIDとは

image.png

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0