Rename files in GDrive programatically with Google Apps Script

The Problem

One of my flatmates was having an issue at work.
He had copied across multiple files in his Google Drive and now had a deeply-nested directory structure with hundreds of files and folders called Copy of.... He didn’t want to go through them manually and rename them all, and asked me if there was a way of removing the prefix automatically. He had done some googling and found some code online, but didn’t know how to run the code.

The Solution

I was aware that Google Apps Scripts had a API which allowed interaction between other Google services, so we used this as a starting point.
You can start a new script yourself here.
We then added Drive API as a service and could use this to target folders of a specific name associated with the authenticated Google user:
notion image
Apps Script uses JavaScript syntax and you can access the Drive API without needing any imports by just calling DriveApp which is accessible in the global scope. DriveApp.getFolderById(`${id}`).getFiles() returns a generator for all the files within a selected folder. Calling .next() on this returns the next file.

The Code

The resulting script was a bit hacky, but we tested it on a nested folder with a few edge cases and also backed up the drive we were going to do the operation on before running the script on it.
In the end, the script timed out for very deep nesting, so he executed it on sub directories rather than the root directory. Additionally, the script doesn’t work well with Copy of Copy of Copy of... files, but it solved the issue for the majority of cases and served its purpose of saving him hours of renaming files.
function myFunction() { var rootFolder = DriveApp.getFoldersByName('Some Unique Name'); recursivelyRenameWithin(rootFolder) }; function recursivelyRenameWithin(folders) { while (folders.hasNext()){ var folder = folders.next(); var files = folder.getFiles(); var subFolders = folder.getFolders(); renameFiles(files); recursivelyRenameWithin(subFolders); }; }; function renameFiles(files) { while(files.hasNext()){ var file = files.next() var fileName = file.getName(); if (fileName.indexOf('Copy of ') !== -1) { fileName = fileName.split('Copy of ')[1]; file.setName(fileName); }; }; };