Skip to content

Snippets · 12 functions

Google Drive snippets

Twelve short functions for the Drive tasks that come up again and again: 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

Look for a folder by name at the top level of Drive and create 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

Get the name of every file directly inside one folder, not counting files in its subfolders.

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

Write a new plain-text file with some content directly into 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

Duplicate an existing file under a new name, leaving the original untouched.

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)

Move a file so it lives in one destination folder, instead of copying it or adding a second parent.

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

Search all of Drive for files that share an exact name and log 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

Read 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

Pull 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

Grant one email address view-only access to a file, the same effect as adding them 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

Read what kind of file it is and how many bytes it takes up, useful before converting or emailing it.

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

Add a new folder inside an existing folder, useful for organizing 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

Turn a Google Doc into a PDF file in memory, ready to email as an attachment or save 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