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.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
Logs the name of every file directly inside one folder. Files in its subfolders are not included.
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
Creates a plain-text file with some content in 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
Copies an existing file under a new name. The original is not changed.
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.
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.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
Logs 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
Pulls 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
Logs the file type and its size in bytes. Check these before you convert or email a file.
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.
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.
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
Copy the attachments from chosen Gmail conversations into one Drive folder. You pick the conversations by adding a label to them, and the script saves every attachment it finds there.
- Task guide Email a Google Doc as a PDF
Send a Google Doc to someone as a PDF attachment. Paste the file ID of the Doc into the script, and it builds the PDF and emails it. The Doc itself is not changed.
- Task guide Fill a Google Doc template from a Sheet row
Make one filled-in copy of a template Doc for each row on a Letters tab. The script swaps {{Name}}, {{Date}}, and {{Amount}} for the values in the row and writes the link to the copy in column D.
- Task guide Back up a spreadsheet to Drive every week
Keep a dated copy of a spreadsheet in a Drive folder. Run the setup function once, and every Monday morning the script saves a new copy with the date in its name.
- 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 say what failed, for example TypeError: Cannot read properties of null (reading 'getRange') or ReferenceError. Find the exact message below for its cause and fix.