List files inside a shared drive folder in spreadsheets - google-apps-script

I am trying to list all the files I have in a shared drive in a spreadsheet with their name and the URL link.
I came across the following Google script
function findFilesInfo() {
const folderId = '1vNaHwTQ2WObU9Hil5GMqXdiokYp5wfDH'
const folder = DriveApp.getFolderById(folderId)
const files = folder.getFiles()
const source = SpreadsheetApp.getActiveSpreadsheet();
const sheet = source.getSheetByName('Sheet2');
const data = [];
while (files.hasNext()) {
const childFile = files.next();
var info = [
childFile.getName(),
childFile.getUrl(),
childFile.getLastUpdated(),
];
data.push(info);
}
sheet.getRange(2,1,data.length,data[0].length).setValues(data);
}
From the following question here
I tried to implement it and it's working for my own personal drive, but when I change the ID to a shared drive, it keeps giving me the following error:
TypeError: Cannot read property 'length' of undefined (line 20, file "get name")
I tried removing the data.length or set a specific number for the getRange function, it all gives me the same error.
Am I doing anything wrong here?

Replace
sheet.getRange(2,1,data.length,data[0].length).setValues(data);
by
if(data.length > 0) sheet.getRange(2,1,data.length,data[0].length).setValues(data);
The above because the error message will occur when the folder hasn't any file.
Related Q/A about working with subfolders
Iterate Through Folders/Subfolders/Files in Google Drive
I need to list all the files in subfolders using google script
How to list also files inside subfolders in google drive
How best to delete all files in a folder and its subfolders

Related

Google App Script File class method getOwner() Always returning null for Google shared Drive files

I am trying to extract file details by using the below app script. It works for all the files saved in my drive or files shared with me by someone else. For shared drives files, var owner = file.getOwner() always returns null. Other than getOwner() all the methods works well even with a shared drive folder. Please suggest if I am doing something wrong here.
Code:
function list_all_files_inside_one_folder_without_subfolders(){
var sh = SpreadsheetApp.getActiveSheet();
var folder = DriveApp.getFolderById('MyFolderID'); // I change the folder ID here
var list = [];
list.push(['Name','ID', 'URL','Size','Upload Date', 'Owner']);
list_all_folders_of_folder(folder,list)
sh.getRange(1,1,list.length,list[0].length).setValues(list);
}
function list_all_folders_of_folder(folder,list){
var subfolder = folder.getFolders();
while (subfolder.hasNext()) {
folder = subfolder.next();
list_all_files_of_folder(folder,list)
}
}
function list_all_files_of_folder(folder,list){
var files = folder.getFiles()
while (files.hasNext()){
file = files.next();
var row = []
var owner = file.getOwner()
Logger.log(file.getName())
Logger.log(owner)
row.push(file.getName(),file.getId(), file.getUrl(), file.getSize(), file.getLastUpdated(), owner.getName() )
list.push(row);
}
}
Kind of expected since using Shared Drive transfers the ownership of the file to the entire organization (Not a user or an email address) and file ownership is removed from the user.
There's a workaround I think that can be implemented but it would require a direct call to DriveAPI to check for file activity (Who created the file) but this is far beyond basic scripting or using advanced Workspace Services on GAS.

Google Apps Script - Impossible operation with an element inside a shared drive

I need your help on something.
I did a function which goal is to make a copy of a template file and put it in a folder in a shared drive. The problem is that the program returns :
"Exception: This operation cannot be performed on an item in a shared Drive"
Yet, I have all the permissions in that shared drive so I don't understand.
I did several tweaks and I've founded that removeFile and addFile are parts of the problem. If I don't run them, the folder is created and the copy is made. But I still need the file to be moved.
I hope someone can help me with this.
PS : You can fin my code below.
function makeCopyFile(folderID, fileID, newName) {
var getFolder = DriveApp.getFolderById(folderID);
var file = DriveApp.getFileById(fileID);
var copyFile = file.makeCopy();
var newFile = copyFile.setName(newName);
// Remove the file from all parent folders
var parents = newFile.getParents();
while (parents.hasNext()) {
var parent = parents.next();
parent.removeFile(newFile);
}
getFolder.addFile(newFile);
};
The problem is that you are trying to delete a file on a shared drive with DriveApp
It will work if you do it instead with the Advanced Drive service where you can specify "supportsAllDrives": true
So, after enabling the Advanced Service: replace
var parents = newFile.getParents();
while (parents.hasNext()) {
var parent = parents.next();
parent.removeFile(newFile);
}
through
var id = copyFile.getId();
// or alternatively `var id = newFile.getId();` - because it is the same
Drive.Files.remove(id,{"supportsAllDrives": true})
As for getFolder.addFile(newFile);
Once you remove a file, you cannot add it back anymore. Also, I do not understand your motivation for it - copyFile.setName(newName); is enough to rename the file - you do not need to delete the file with the old name and insert the one with the new name.
UPDATE
If your goal is to copy a file to a team drive folder, you can do it easily as following with the Drive API:
function makeCopyFile(folderID, fileID, newName){
var resource = {
"parents": [
{
"id": folderID
}
],
"title": newName
}
Drive.Files.copy(resource, fileID, {"supportsAllDrives": true})
}

Google Spredsheet - Copy files to another folder in TeamDrive

I try to copy some movies from a Google Drive folder to another Folder and rename the file by using a script in a Spreadsheet. (other options than spreadsheets are also welcome, but this seems to be easyest). I got access on both folders.
a) is working as it should, makeing a copy of the file in the same folder;
b) is also doing a copy but still in the same folder and not in the destination-folder;
c) giving error:
"cannot find method makeCopy(string,string)"
function copyFile() {
var FileToCopy=DriveApp.getFileById('12B-zfprxgazbZ4JFxyrqhYveofYATzC1');
FileToCopy.makeCopy()
}
function copyFile() {
var FileToCopy=DriveApp.getFileById('12B-zfprxgazbZ4JFxyrqhYveofYATzC1');
var Destination = "1yC_nDk9VQLHBAkYNwNkRucfxp6yFBIV1";
FileToCopy.makeCopy(Destination)
}
function copyFile() {
var FileToCopy=DriveApp.getFileById('12B-zfprxgazbZ4JFxyrqhYveofYATzC1');
var Destination = "1yC_nDk9VQLHBAkYNwNkRucfxp6yFBIV1";
var Filename = "newFile.mp4";
FileToCopy.makeCopy(Filename, Destination)
}
Instead of
var Destination = "1yC_nDk9VQLHBAkYNwNkRucfxp6yFBIV1";
try
var Destination = DriveApp.getFolderById("1yC_nDk9VQLHBAkYNwNkRucfxp6yFBIV1");
If you see the documentation, you need to pass the folder and not the ID of the destination folder.

"Cannot find function getFiles in object test" error when trying to list pdf file in a drive folder

I'm trying to run this (very) simple script :
function listFilesInFolder() {
var folder = DriveApp.getFileById('XXXXXXXXXXXXXXXX');
Logger.log(folder.getName());
var contents = folder.getFiles();
};
but I have the following error
TypeError: Cannot find function getFiles in object testupwork. (line 4, file "Code")
Log is working properly
While on Google Drive REST API file is used both for handling files and folders on the Apps Script Drive Service there are a specific class for files and another for folders.
Change
var folder = DriveApp.getFileById('XXXXXXXXXXXXXXXX');
to
var folder = DriveApp.getFolderById('XXXXXXXXXXXXXXXX');
Reference
https://developers.google.com/apps-script/reference/drive/drive-app#getfolderbyidid

Using a cell value in Google Sheets as an input to move a file from one folder to another using Google App Script

I have been researching the site but can't find the solution to my question. I a writing a script to extract a list of one or more filenames from a sheet and use these filenames as input to move the actual files from one folder to another in Drive. My issue now is that I don't know how to handle the value "Fileiterator" that is coming back in my script. As a result, the error I am getting when I run my script is "TypeError: Cannot find function makeCopy in object FileIterator"
I'm not sure if I am missing something when I am using the MakeCopy() method or setting up the variable pulling values from the sheet?
here is my code:
// Access Mailing List sheet in gdrive and get filename
var spreadsheet = SpreadsheetApp.openByUrl('spreadsheetURL');
var sheet = spreadsheet.getSheets()[0];
var value = sheet.getSheetValues(2,39,1,1);
Logger.log(value);
var folder = DriveApp.getFolderById("folderid1");
Logger.log(folder);
var files = DriveApp.getFilesByName(value);
Logger.log(files);
var destination = DriveApp.getFolderById("folderid2");
Logger.log(destination);
newfile = files.makeCopy("copy of"+files,destination);
Logger.log(newfile);
Please advise!
The problem occurs because getFilesByName(name) returns a FileIterator object but makeCopy is a File object method.
Example:
This shows how to use a file iterator.
var name = 'File name';
var destination = DriveApp.getFolderById("folderId");
var files = DriveApp.getFilesByName("File name");
while (files.hasNext()) {
var file = files.next();
file.makeCopy("copy of " + name, destination);
}