Home > Software design >  Prevent Duplicate Google Script Copy A File with Filenames from Range
Prevent Duplicate Google Script Copy A File with Filenames from Range

Time:04-03

I can copy a file and rename new copy from spreasheet range. How to not create existing filename if I re-execute the script.

function copyDocs() {
  var file = SpreadsheetApp.openById('fileID-spreadsheet');
  var ss = file.getSheetByName('List');
  var data = ss.getRange(2,1,ss.getLastRow()-1,1).getValues();

  for (var i in data) {
    var drive = DriveApp.getFileById('fileID-template');
    drive.makeCopy(data[i][0]);
  };
}

Here is my final script based on the answers

function copyDocs() {
  try {
    let spread = SpreadsheetApp.openById('fileID-spreadsheet');
    let sheet = spread.getSheetByName('List');
    let data = sheet.getRange(2,1,sheet.getLastRow()-1,1).getValues();
    let file = DriveApp.getFileById('fileID-template');
    let folder = file.getParents().next();

    for( let i=0; i<data.length; i   ) {
      let files = folder.getFilesByName(data[i][0]);
      if( !files.hasNext() ) {
        file.makeCopy(data[i][0],folder);
      }
    }
  }
  catch(err) {
    console.log(err);
  }
}

CodePudding user response:

Description

Here is a simple example of copying a file but checking that a file of that name doesn't already exist.

This assumes the files are in a subfolder, the same folder as the template file. It also assumes there can be only one file with the same file name.

I've used my files so you need to check any file/spreadsheet reference against your requirements.

Script

function copyDocs() {
  try {
    let spread = SpreadsheetApp.getActiveSpreadsheet();
    let sheet = spread.getSheetByName("Sheet1");
    let data = sheet.getDataRange().getValues();

    for( let i=0; i<data.length; i   ) {
      let file = DriveApp.getFileById(spread.getId());
      let folder = file.getParents().next();
      let files = folder.getFilesByName(data[i][0]);
      if( !files.hasNext() ) {
        file.makeCopy(data[i][0],folder);
      }
    }
  }
  catch(err) {
    console.log(err);
  }
}

Reference

]4

  • Related