Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
This Function gets the necessary data from the spreadsheet.
function getSpreadsheetData() {
// get spreadsheet
var ss = SpreadsheetApp.getActiveSheet();
// get folder Id
var folderId = ss.getRange(6, 4).getValue();
Logger.log('Folder Id is: ' + folderId);
// get search pattern
var searchString = ss.getRange(10, 4).getValue();
Logger.log('Search string is: ' + searchString);
// get string to replace with
var replaceString = ss.getRange(14, 4).getValue();
Logger.log('Replace with string is: ' + replaceString);
// run Function to rename files
renameFiles(folderId, searchString, replaceString);
This Function gets the Google Drive folder and iterates through each file. It first
gets the file name, uses 'replace' to search and alter the desired string, then
uses 'setName' to alter the file name to its new value.
function renameFiles(folderId, searchString, replaceString) {
// get spreadsheet for toast notifications
var ss = SpreadsheetApp.getActiveSpreadsheet();
// get Google Drive folder
try {
var parentFolder = DriveApp.getFolderById(folderId);
var gotParent = true;
// create toast popup to inform user
ss.toast('Task has now started ...', 'Start');
catch(e) {
Logger.log('Error getting Google Drive folder: ' + e);
var gotParent = false;
// proceed IF successfully get Google Drive folder
if (gotParent) {
// get sub-files
var subFiles = parentFolder.getFiles();
// cycle through each sub-file to get relevant details
while (subFiles.hasNext()) {
// get sub-file
var subFile =;
// get sub-file name
var subFileName = subFile.getName();
Logger.log('Sub-file name is: ' + subFileName);
// create new sub-file name
var newName = subFileName.replace(searchString, replaceString);
Logger.log('Sub-file new name will be: ' + newName);
// set new sub-file name
// create toast popup to inform user
ss.toast('Task has now completed.', 'Finished');
else {
// display popup error to inform user unable to get Google Drive folder
var ui = SpreadsheetApp.getUi();
var result = ui.alert(
'Google Drive folder error',
'Unable to get Google Drive folder please check correct ID',
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment