[英]Unable to figure out how to move a file to a folder after they have been matched based on an ID that they both have in their names Google apps script
在 Google Drive 中,我試圖將文件名中的 id 與以該 id 命名的文件夾進行比較,如果它們匹配,則將該文件移動到該文件夾。
該程序必須解決的一些問題是:
使這更容易的事情:
到目前為止,我已經成功編寫了一個代碼:
我在“files”文件夾中創建了兩個文件進行測試,“john1111_test.pdf”和“thomas2222_test.pdf”,以及“childName”文件夾中的兩個文件夾“john1111”和“thomas2222”
我堅持的部分是將文件復制到與之匹配的文件夾中。
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);
}
我收到一條錯誤消息,指出 foldermatch.addFile 不是函數。 我也嘗試過 cdName.addFile(element) 。
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
}
}
}
前:
后:
需要啟用 Drive API 版本 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.