1
votes

I'm trying to rename a .pdf file in a google drive folder with Google App Script.

function findFilesInFolder() {
    var childrenData = Drive.Children.list('XXXXXXX')
    var children = childrenData.items;

    //loops through the children and gets the name of each one
    for (var i = 0; i < children.length; i++){
      var id = children[i].id;
      var file = Drive.Files.get(id);
      file.setName('testname');
    }
  }

Looking at this doc https://developers.google.com/apps-script/reference/drive/file#setName(String) setName is the right method to use.

2
For some reason your file is not valid. Log the id After this line: var id = children[i].id; Add: Logger.log('id: ' + id) Run the code, then from the View menu, choose Logs. If there is no id or if there is no file with that id then the variable file may not be a valid file. - Alan Wells
Log is working ok. I have some file id. Actually I've already log the title of each file and It's working. So I think the issue is somewhere else. - Simon Breton
Are you using setName somewhere else? - Alan Wells

2 Answers

2
votes

You are confusing your file objects. Your code uses the Drive "advanced service" to obtain file metadata, and does not use the native "Drive Service" via DriveApp (an implementation of the Drive REST API that provides fewer features in exchange for being easier to use) to get a File-class object.

If you want to use the native DriveApp#File#setName method, then instead of using the Drive method Drive.Files.get use DriveApp.getFileById, once you have the relevant id value:

Changing the name via DriveApp#setName:

for (var i = 0; i < children.length; i++){
  var id = children[i].id;
  var file = DriveApp.getFileById(id);
  file.setName('testname');
}

Changing the name with Drive advanced service:

for (var i = 0; i < children.length; i++){
  var fileData = children[i];
  fileData.title = "testname";
  Drive.Files.patch(fileData, fileData.id);
}
1
votes

You have to use the API's call. For an example update.

Drive.Files.update({title: 'new title'}, id)

The next code should work fine for you.

function renameFiles_(title, newTitle) {
  return Drive.Files.list({
    q: Utilities.formatString("title='%s'", title)
  }).items.map(function(item) {
    return Drive.Files.update({
      title: this.newTitle
    }, item.id)
  }, {
    newTitle: newTitle
  });
}

function test(){
  Logger.log(renameFiles_("XXXXXXX", "testname"));
}