There are times when you want to automatically rename files using Google Apps Script in a folder specially when you are working on some automated task. Google Apps Script with the power of Google Cloud Platform has a lot of positives like you can write it on the web, run on the web and also it doesn’t required any hardware and software setups like other programming languages do.
Let’s see the code which will help you out in rename files using Google Apps Script present in a folder on Google Drive and then understand whats happening in that code.
function FileRenaming() { var SourceFolder = DriveApp.getFolderById("Add your Source Folder ID") var Files = SourceFolder.getFiles(); while(Files.hasNext()) { var file = Files.next(); var FileRename = file.makeCopy(file.getName() + '.' + Utilities.formatDate(new Date(), Session.getScriptTimeZone(), 'yyyy-MM-dd HH:mm:ss')); var DestinationFolder = DriveApp.getFolderById("Add your Destination Folder ID") DestinationFolder.addFile(FileRename); SourceFolder.removeFile(file); } }
Now let’s try to understand the code :
Here in above code what we are doing is that, initially we create a variable named Source Folder and pass the id of that folder. Then we iterate over it and get all the files that are present in that Source Folder. Next we create a copy with the desired name (after renaming) of the files present in the Source Folder and pass it to the variable File Rename. Here, Utilities.formatDate(date, timeZone, format) formats date according to specification we pass as shown in the above code. Finally we pass the id of the destination folder id where we want to move the renamed files and ultimately delete the files from the source folder.
To get more detailed knowledge about Google Apps Script, you can check the official website. Also if you want to explore more codes/posts related to Google Apps Script on our website, then you can find it here.
If you have any questions or if you need any help please get in touch with me using the comment section below.
paahek says
How to rename new files in source folder, the old files should remain in folder.