GAS googleドライブの指定したidのファイルを取得する

GAS googleドライブの指定したidのファイルを取得する

GAS(Google Apps Script)で、googleドライブの指定したidのファイルを取得する手順を記述してます。「DriveApp.getFileById()」を使用します。存在しないidを指定するとエラーが発生します。

環境

  • OS windows11 home
  • ブラウザ chrome 110.0.5481.104

指定したidのファイルを取得

指定したidのファイルを取得するには、「DriveApp.getFileById()」を使用します。

DriveApp.getFileById(id)

ファイルのidは、共有のリンクから確認可能です。

リンクをコピーをクリックします。

選択している箇所が、idとなります。

実際に、id名を指定して、そこからファイル名を取得してみます。

function myFunction() {

  // idから取得
  const file = DriveApp.getFileById('12tcFe7ceGxxxxxxxxxxxxxxxxx');

  // ファイル名を取得
  console.log(file.getName());

}

ファイル名が取得されていることが確認できます。

存在しないidを指定

存在しないidを指定すると、エラーが発生します。

function myFunction() {

  // idから取得
  const file = DriveApp.getFileById('xxxxxxxxxxxxxxxxxxxxx');
  // Exception: Unexpected error while getting the method or property getFileById on object DriveApp.

  // ファイル名を取得
  console.log(file.getName());

}