Skip to content

Snippets · 12 functions

Google Drive snippets

Twelve short functions for common Drive tasks with folders, files, copies, and sharing.

How to use these

Set up before you run

Copy a snippet into a script file, read its setup and notes, change the placeholder values, and save. For functions meant to run manually, choose the function name in the toolbar and press Run. Results appear in the Execution log unless the description says otherwise.

1

Get a folder by name or create it

Looks for a folder by name at the top level of Drive and creates it only when it does not already exist.

DriveApp.FolderDriveApp.FolderIterator
Code.gs
function getOrCreateReportsFolder() {
  const folderName = 'Reports';
  const rootFolder = DriveApp.getRootFolder();
  const existingFolders = rootFolder.getFoldersByName(folderName);
  if (existingFolders.hasNext()) {
    const folder = existingFolders.next();
    Logger.log('Using existing folder: ' + folder.getUrl());
    return;
  }
  const folder = rootFolder.createFolder(folderName);
  Logger.log('Created folder: ' + folder.getUrl());
}

Good to know. getFoldersByName can match more than one folder if you have duplicates, so this only checks the first result.

2

List files in a folder

Logs the name of every file directly inside one folder. Files in its subfolders are not included.

DriveApp.FolderDriveApp.FileIterator
Code.gs
function logFilesInReportsFolder() {
  const folders = DriveApp.getFoldersByName('Reports');
  if (!folders.hasNext()) throw new Error('Create a Drive folder named Reports before running this function.');
  const folder = folders.next();
  const files = folder.getFiles();
  const names = [];
  while (files.hasNext()) {
    names.push(files.next().getName());
  }
  Logger.log(names);
}

3

Create a text file in a folder

Creates a plain-text file with some content in a specific folder.

Code.gs
function createNotesFile() {
  const folders = DriveApp.getFoldersByName('Reports');
  if (!folders.hasNext()) throw new Error('Create a Drive folder named Reports before running this function.');
  const folder = folders.next();
  const file = folder.createFile('Notes.txt', 'Created by Apps Script.');
  Logger.log('Created file: ' + file.getUrl());
}

4

Make a copy of a file

Copies an existing file under a new name. The original is not changed.

Code.gs
function copyFileWithNewName() {
  const fileId = 'REPLACE_WITH_FILE_ID';
  const file = DriveApp.getFileById(fileId);
  const copy = file.makeCopy('Copy of ' + file.getName());
  Logger.log('Created copy: ' + copy.getUrl());
}

5

Move a file into a folder (moveTo)

Moves a file into one destination folder. The file is not copied, and it ends up in that folder only.

Code.gs
function moveFileToReportsFolder() {
  const fileId = 'REPLACE_WITH_FILE_ID';
  const file = DriveApp.getFileById(fileId);
  const folders = DriveApp.getFoldersByName('Reports');
  if (!folders.hasNext()) throw new Error('Create a Drive folder named Reports before running this function.');
  const destination = folders.next();
  file.moveTo(destination);
  Logger.log('Moved ' + file.getName() + ' to ' + destination.getName());
}

6

Find files by name

Searches all of Drive for files with an exact name and logs how many were found.

DriveApp.FileIteratorDriveApp.File
Code.gs
function findFilesNamedNotes() {
  const files = DriveApp.getFilesByName('Notes.txt');
  const found = [];
  while (files.hasNext()) {
    found.push(files.next().getId());
  }
  Logger.log('Found ' + found.length + ' file(s): ' + found.join(', '));
}

Good to know. This matches the exact file name, so it will miss files with extra spaces or a different capitalization.

7

Get a file's URL and ID

Logs the link and the unique ID of a file, so you can store either one, such as in a Sheet row.

Code.gs
function logFileUrlAndId() {
  const fileId = 'REPLACE_WITH_FILE_ID';
  const file = DriveApp.getFileById(fileId);
  Logger.log('URL: ' + file.getUrl());
  Logger.log('ID: ' + file.getId());
}

8

Get the ID from a Drive URL with a regex

Pulls the file ID out of a full Drive link, such as one pasted into a Sheet cell.

Code.gs
function extractFileIdFromUrl() {
  const url = 'https://drive.google.com/file/d/REPLACE_WITH_FILE_ID/view';
  const match = url.match(/[-\w]{25,}/);
  if (!match) throw new Error('Could not find a file ID in that URL.');
  Logger.log('Extracted ID: ' + match[0]);
}

9

Share a file with one person as a viewer

Gives one email address view-only access to a file, the same as adding that person as a Viewer in the Share dialog.

Code.gs
function shareFileAsViewer() {
  const fileId = 'REPLACE_WITH_FILE_ID';
  const viewerEmail = 'you@example.com';
  const file = DriveApp.getFileById(fileId);
  file.addViewer(viewerEmail);
  Logger.log('Shared ' + file.getName() + ' with ' + viewerEmail);
}

Good to know. Only share files with people who have agreed to receive them, since addViewer shares immediately and Google may email that person a sharing notice.

10

Get a file's MIME type and size

Logs the file type and its size in bytes. Check these before you convert or email a file.

Code.gs
function logFileMimeTypeAndSize() {
  const fileId = 'REPLACE_WITH_FILE_ID';
  const file = DriveApp.getFileById(fileId);
  Logger.log('Type: ' + file.getMimeType());
  Logger.log('Size in bytes: ' + file.getSize());
}

11

Create a subfolder

Creates a folder inside an existing folder, for example to sort files by month or by project.

Code.gs
function createArchiveSubfolder() {
  const folders = DriveApp.getFoldersByName('Reports');
  if (!folders.hasNext()) throw new Error('Create a Drive folder named Reports before running this function.');
  const parent = folders.next();
  const subfolder = parent.createFolder('Archive');
  Logger.log('Created subfolder: ' + subfolder.getUrl());
}

12

Convert a Google Doc to PDF blob

Converts a Google Doc into PDF data in memory and logs its size. You can then email the PDF as an attachment or save it to Drive.

Code.gs
function convertDocToPdfBlob() {
  const documentId = 'REPLACE_WITH_DOCUMENT_ID';
  const file = DriveApp.getFileById(documentId);
  const pdfBlob = file.getAs('application/pdf');
  Logger.log('PDF blob ready, size in bytes: ' + pdfBlob.getBytes().length);
}

Keep going

See these in a complete task

All snippet collections