Reputation: 21
I made a google app script (in my google sheet, actually doesn't relevant to it at all) for the following series of actions
I manually uploaded some files (~50 files) to a google drive folder called "source folder", then I want to use these 50 files to overwrite another 50 files with same name under another google drive folder, let say "target folder".
Why i need to do this instead of dragging all the files directly onto the "target folder" in google drive through the browser drag and drop? Because sometimes, some file are very strange, they can't be replaced/overwrite, they will create another new file then my "target folder" will have 2 file have the same name.
In the middle part of my code, i have the following to check the file name matches between source files and target files...
var existing = folder.getFilesByName(sourcefilename);
// Does file exist?
if (existing.hasNext()) {
var file = existing.next();
// Make sure the file name is exactly the same
if (file.getName() === sourcefilename) {
Logger.log("Overwrite: "+sourcefilename);
// Updates file metadata and/or content with the Drive API
Drive.Files.update({
title: file.getName(), mimeType: file.getMimeType()
}, file.getId(), sourcefile.getBlob());
}
}
My problems randomly appears, it sometimes cannot get the variable "existing" and then it fails to enter the if condition after it. I tried a few times, the longer i wait, the higher success chance it is. Sometimes i run in debug mode, run it line by line, most of the case it works fine.
I don't know why the code randomly works fine.
Can someone point me to a right direction to fix that and make sure 100% work? Thanks
Upvotes: 0
Views: 344
Reputation: 64072
This works for me:
function getsomefiles(name='Doc1') {
const folder=DriveApp.getFolderById('folderid');
let existing = folder.getFilesByName(name);
let fA=[];
if (existing.hasNext()) {
var file = existing.next();
fA.push(file.getId());
}
if(fA.length>0)SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(fA.join(',')),'title');
}
Upvotes: 1