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.FolderIteratorfunction 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.FileIteratorfunction 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.
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.
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.
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.Filefunction 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.
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.
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]);
} 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.
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.
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.
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
- Task guide Save labeled Gmail attachments to Drive
Choose the email threads yourself by adding a Gmail label, then copy their attachments into an existing Drive folder.
- Task guide Email a Google Doc as a PDF
Give the script the file ID of a Doc. It makes a PDF copy and emails it as an attachment. The Doc itself is not changed.
- Task guide Fill a Google Doc template from a Sheet row
Each row that has no link yet gets its own copy of your template Doc, with the placeholders swapped for the values in that row. The link to the copy goes back in the last column.
- Task guide Back up a spreadsheet to Drive every week
Run the setup function once. Every Monday morning the script copies the spreadsheet into a Drive folder and puts the date in the copy name. The original is never touched.
- Basics Apps Script permissions and authorization
Before a script can read your sheet or send your mail, you give it permission to access a list of OAuth scopes. This page walks through each authorization screen, explains @OnlyCurrentDoc, and shows how to revoke access.
- Basics Common Apps Script errors and what they mean
Apps Script error messages name the failure directly, from TypeError: Cannot read properties of null (reading 'getRange') to ReferenceError and quota limits. Find the exact message below for the cause and fix.