Reputation: 11
I am looking for a script that loops through a google sheet and renames the files in a folder on google drive.
The sheet has the location of the file in drive and the name of the original file and the new name of the file.
Since I am a complete beginner at google script and javascript i would be enternal grateful if someone could help me with this.
Upvotes: 0
Views: 4671
Reputation: 64032
I didn't have anything to do so I thought I'd give it a try. I only tested it once and it doesn't interact with the user. So here it is.
function renameFiles(shname){
//var shname=shname||'bullSheet';
if(shname){
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(shname);
var rg=sh.getDataRange();
var vA=rg.getValues();
var folderId=getFolderId(shname);
if(vA.length>2){
var nameA=[];
var idA=[];
var fldr=DriveApp.getFolderById(folderId);
var files=fldr.getFiles();
while(files.hasNext()){
var file=files.next();
nameA.push(file.getName());
idA.push(file.getId());
}
for(var i=2;i<vA.length;i++){
var idx=nameA.indexOf(vA[i][0]);
if(!vA[i][2] && vA[i][1] && vA[i][0] && idx>-1){
DriveApp.getFileById(idA[idx]).setName(vA[i][1]);
vA[i][2]='RENAMED';
}
}
rg.setValues(vA);
}else{
var fA=[];
var fldr=DriveApp.getFolderById(folderId);
var files=fldr.getFiles();
while(files.hasNext()){
var file=files.next();
sh.appendRow([file.getName()]);
}
}
}
}
function getFolderId(shname){
var ss=SpreadsheetApp.getActive();
var sh=ss.getSheetByName(shname);
var rg=sh.getDataRange();
var vA=rg.getValues();
return vA[0][1];
}
Here's the spreadsheet when you start. It has the folder id in B1 and three headers on line 2 and nothing else.
Then you run renameFiles the first time and it reads the files in the directory whose id is in B2 and puts them on the spreadsheet.
Then you enter the new names for these files in column 2 under the headers.
Then run the program again and it renames the files to your new names and puts "RENAMED" in column 3 which keeps the program from doing anything if you run it again.
There's still quite a bit that you might wish to add like dialogs that tell the user what's going on but I'll leave that as an exercise for you.
If you have a lot of files in a directory you may have to add page tokening to the process. I chose not to do that because I'm basically lazy.
If your wondering where to get the folder id then go to the folder in google drive and look at the url. It's the longest section in the url
Upvotes: 3