在 Google Drive 中,我試圖將檔案名中的 id 與以該 id 命名的檔案夾進行比較,如果它們匹配,則將該檔案移動到該檔案夾??。
該程式必須解決的一些問題是:
- 由于 id 是根據客戶姓名生成的,因此沒有設定長度
- id 可以在檔案名中的任何位置,而不僅僅是在開頭或結尾
- 可以有多個不同名稱的檔案包含相同的id,所以程式必須回圈
使這更容易的事情:
- 所有檔案夾都在同一個父檔案夾中,并以 id 作為名稱,因此程式可以使用檔案夾名稱串列作為 id 串列
- 檔案都在同一個父檔案夾中,檔案夾中不會有其他檔案,所以回圈可以一直運行到檔案夾為空
到目前為止,我已經成功撰寫了一個代碼:
- 按 id 訪問兩個父檔案夾
- 遍歷檔案夾,直到檢查完所有檔案,并將檔案名推送到名為“fileNames”的陣列中
- 遍歷檔案夾并將當前檔案夾的名稱與檔案名進行比較以進行匹配,并將檔案夾名稱推送到名為“childNames”的陣列中
我在“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) 。
任何幫助,將不勝感激
uj5u.com熱心網友回復:
移動檔案
function movingFile() {
const files = DriveApp.getFolderById('files folder id');
const folders = DriveApp.getFolderById('folders folder id');
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('_')))) {//iif 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('_')));
Drive.Files.update({"parents": [{"id": f.getId()}]}, file.getId());
}
}
}
前:


后:


需要啟用 Drive API 版本 2
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/444225.html
上一篇:多行文本輸入的標簽損壞?
下一篇:Apps腳本“OR”邏輯運算子
