Reputation: 31
Good morning, I am running into some issues when creating a google app scripts to remove all files/folders from the root of the Google Drive. I have found the following code but it appears to error out when running;
function deleteFile(idToDLET) {
idToDLET = 'the File ID';
//This deletes a file without needing to move it to the trash
var rtrnFromDLET = Drive.Files.remove(idToDLET);
}
Error Code = Script function not found; myFunction
Thanks
Upvotes: 3
Views: 6963
Reputation: 1
delete all file in folder with a id of folder input!
function deleteAllFile() {
// Get all files in Drive
const idFolder = 'id'
var files = DriveApp.getFolderById(idFolder).getFiles();
// Delete every file
while (files.hasNext()) {
var file = files.next();
Logger.log('Deleting file "%s"',
file.getName());
// Delete File
DriveApp.getFolderById(idFolder).getFilesByName(file.getName()).next().setTrashed(true)
}
}
Upvotes: 0
Reputation: 1865
Thanks to @CTOverton answer, I've created another version as I noticed that a File has the setTrashed method, which moves the file in the trash bin.
If the Drive has important files saved, I'd suggest to move files to trash instead of doing a permanent deletion, it may save you from a disaster while doing scripting experiments :-)
This version uses a folder id which you can get with: folder.getId()
.
You can use CTOverton's code to delete all files on your Drive (commented).
function emptyFolder(folderId) {
const folder = DriveApp.getFolderById(folderId);
while (folder.getFiles().hasNext()) {
const file = folder.getFiles().next();
Logger.log('Moving file to trash: ', file);
file.setTrashed(true);
// Delete File
//Drive.Files.remove(file.getId())
}
}
Cheers
Upvotes: 3
Reputation: 686
As @James D said, you are missing the myFunction which is the default function in order to run the script. Make sure to save your script first.
Here is the code to get all the files and delete them.
function myFunction() {
// Get all files in Drive
var files = DriveApp.getFiles();
// Delete every file
while (files.hasNext()) {
var file = files.next();
Logger.log('Deleting file "%s"',
file.getName());
// Delete File
Drive.Files.remove(file.getId())
}
}
In order to use DriveAPI, you need to add it through the Resources>Advanced Google Services menu. Set the Drive API to ON. AND make sure that the Drive API is turned on in your Google Developers Console. If it's not turned on in BOTH places, it won't be available.
Apps scripts are stored as files in Google Drive...
This script upon running will remove any and all files in the connected google drive account, including itself.
Hope this helps!
Upvotes: 2