當我使用 DriveApp.getFolderById(someId)someId屬于檔案而不是檔案夾時,該方法回傳檔案而不是錯誤。如何確保回傳的物件確實是一個檔案夾?
現在,我能想到的唯一解決方案是使用 try/catch:
try {
const testFile = someFile.makeCopy('test', folder);
testFile.setTrashed(true);
} catch (err) {
return 'The folder is not really a folder';
}
有更清潔的解決方案嗎?
uj5u.com熱心網友回復:
例如,在您的情況下,如何檢查 mimeType 如下?
示例腳本:
const id = "###"; // Please set the file ID and folder ID.
const file = DriveApp.getFileById(id);
if (file.getMimeType() == MimeType.FOLDER) {
console.log(`This ID (${id}) is a folder.`);
const folder = DriveApp.getFolderById(id);
// Do something.
} else {
console.log(`This ID (${id}) is not a folder.`);
}
- 運行此腳本時,通過查看 的 mimeType
id,可以查看 ID 是否為檔案夾。
參考:
- 獲取MimeType()
添加:
從您的以下回復中,
檔案夾沒有要呼叫的 getMimeType 函式,所以我猜像 if (!folder.getMimeType) 這樣的檢查 a 回傳 true 表明它是一個檔案夾。
如果你想檢查 using const folder = DriveApp.getFolderById(id),下面的示例腳本怎么樣?
示例腳本:
const id = "###"; // Please set the file ID and folder ID.
const folder = DriveApp.getFolderById(id);
if (folder.getUrl().split("/")[4] == "folders") {
console.log(`This ID (${id}) is a folder.`);
// In this case, you can directly use the variable of "folder".
// Do something.
} else {
console.log(`This ID (${id}) is not a folder.`);
}
- In this sample script, by checking the URL of the object, it is checked whether
idis the folder. For example, whenidis Spreadsheet, the retrieved URL is likehttps://docs.google.com/spreadsheets/d/###/edit?usp=drivesdk. This script uses this situation.
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/452739.html
