Search for Files in Google Drive

Apps Script provides DriveApp.searchFiles(query) and DriveApp.searchFolders(query), which accept Google Drive search query syntax. This lets you find files by name, type, creation date, owner, and more — without manually browsing your Drive.

Basic File Search by Name

function findFileByName() { var files = DriveApp.searchFiles('title contains "Sales Report"'); while (files.hasNext()) { var file = files.next(); Logger.log(file.getName() + " | " + file.getUrl()); } }

Search by File Type

function findAllPDFs() { var files = DriveApp.searchFiles('mimeType = "application/pdf"'); while (files.hasNext()) { var file = files.next(); Logger.log(file.getName()); } }

Search by Date Created

Find all files created after March 1, 2024:

function findRecentFiles() { var files = DriveApp.searchFiles('createdDate > "2024-03-01T00:00:00"'); while (files.hasNext()) { var file = files.next(); Logger.log(file.getName() + " | Created: " + file.getDateCreated()); } }

Searching for Customer Contracts from Sheet Data

This example reads customer names from the Sales Tracker and searches Drive for each customer's contract file, logging whether it was found:

function auditCustomerContracts() { var sheet = SpreadsheetApp .getActiveSpreadsheet() .getSheetByName("Sales Tracker"); var data = sheet.getRange(2, 1, sheet.getLastRow() - 1, 7).getValues(); // Columns: [Customer Name, Email, Product, Amount, Region, Sales Rep, Status] data.forEach(function(row) { var customerName = row[0]; var status = row[6]; if (status !== "Closed") return; var query = 'title contains "' + customerName + '" and title contains "Contract" and trashed = false'; var results = DriveApp.searchFiles(query); if (results.hasNext()) { var file = results.next(); Logger.log("Found contract for " + customerName + ": " + file.getUrl()); } else { Logger.log("Missing contract for: " + customerName); } }); }

With the sample data, it checks for contracts for Sarah Johnson and Lisa Park (both Closed) and logs a warning if any are missing.

Combining Multiple Search Conditions

Use and / or to combine conditions:

function findRecentCustomerDocs() { var query = [ 'title contains "Pro Plan"', 'mimeType = "application/vnd.google-apps.document"', 'createdDate > "2024-03-01T00:00:00"', 'trashed = false' ].join(' and '); var files = DriveApp.searchFiles(query); while (files.hasNext()) { var file = files.next(); Logger.log(file.getName()); } }

Searching Within a Specific Folder

To limit results to a folder, use "FOLDER_ID" in parents:

function searchInNorthFolder() { var folderId = "YOUR_NORTH_FOLDER_ID"; var query = '"' + folderId + '" in parents and title contains "2024"'; var files = DriveApp.searchFiles(query); while (files.hasNext()) { Logger.log(files.next().getName()); } }