In Google Drive I am trying to compare an id in a file name against folders named with that id, and if they match, to move that file to that folder.
Some of the problems that the program has to account for are:
Things that make this easier:
So far I have written a code that successfully:
I have created two files in the "files" folder to test with, "john1111_test.pdf" and "thomas2222_test.pdf", and two folders in the "childName" folder "john1111" and "thomas2222"
The part that I am stuck on is copying the file to the folder it matched with.
var childFolder = DriveApp.getFolderById('****').getFolders(); // Folder containing folders
var files = DriveApp.getFolderById('****').getFiles(); // Folder containing the files
var fileNames = [];
while (files.hasNext()) {
var file1 = files.next();
var fName = file1.getName()
Logger.log(fName);
fileNames.push(fName);
}
var childNames = [];
while (childFolder.hasNext()) {
var child = childFolder.next();
var cdName = child.getName();
Logger.log(cdName);
childNames.push(cdName);
const match = fileNames.find(element => {
if (element.includes(cdName)) {
// This is the area that I am having issues with
let folderMatch = childFolder.getFoldersByName(cdName);
let fileMatch = files.getFilesByName(element);
folderMatch.addFile(fileMatch)
return true;
}
});
console.log(match);
}
I receive an error saying that foldermatch.addFile is not a function. I have tried cdName.addFile(element) as well.
function movingFile() {
const files = DriveApp.getFolderById('1jeAihkCiA--EfAl150IXrXDUa-MhYSKY');
const folders = DriveApp.getFolderById('1xB4XTG8d1DYtthVQQqkSQCqvzv-TGWtW');
const fldrs = folders.getFolders();
let fldrNames = [];
let fldrA = [];
while (fldrs.hasNext()) {
let fldr = fldrs.next()
fldrNames.push(fldr.getName());
fldrA.push(fldr);
}
const fs = files.getFiles();
while (fs.hasNext()) {
let file = fs.next();
let idx = fldrNames.indexOf(file.getName().slice(0,file.getName().indexOf('_')));
if(~fldrNames.indexOf(file.getName().slice(0,file.getName().indexOf('_')))) {//if folder is present move it here
//SpreadsheetApp.getUi().alert(file.getName().slice(0,file.getName().indexOf('_')));
Drive.Files.update({"parents": [{"id": fldrA[idx].getId()}]}, file.getId());
} else {//if it is not then create it first and xfer
let f = folders.createFolder(file.getName().slice(0,file.getName().indexOf('_')));
fldrA.push(f);
Drive.Files.update({"parents": [{"id": f.getId()}]}, file.getId());
fldrNames.push(file.getName().slice(0,file.getName().indexOf('_')));//added folder name to fldrNames so that it will be used again if there are more files with that name
}
}
}
Before:
After:
Need to enable Drive API Version 2