How to move a file from MyDrive to Team Drive? - google-apps-script

I would like to use Google Apps Script to transfer a file from MyDrive to Team Drive. I can do this manually (so I know I have permission) and I enabled the Drive API (so was able to save to MyDrive). However, when I do this (which I got from another post):
function moveFileToFolder(fileId, newFolderId) {
var file = Drive.Files.get(fileId, {supportsTeamDrives: true});
Drive.Files.patch(file, fileId, {
supportsTeamDrives: true,
corpora: 'teamDrive',
removeParents: file.parents.map(function(f) { return f.id; }),
addParents: [newFolderId],
});
}
I get this error:
Sharing restrictions cannot be set on a Team Drive item.
Any ideas?

It appears I was overthinking it as the following works:
var file = DriveApp.getFileById(fileId);
var parentFolder = DriveApp.getFolderById(TEAM_DRIVE_ID);
parentFolder.addFile(file);

Related

Exporting folder information from Shared Drive; Issue with pageToken

I'm attempting to export the folder name, folder id, folder url, and filepath for folders within a Shared Drive. This part works, but I'm limited to 100 items. I'm attempting to use the pageToken/nextPageToken functionality to pull all items, but it doesn't seem to work and continues returning only 100 items. I'm using the same basic structure as google uses in their example code for this purpose and was also referencing this solution to a similar problem.
function getFolderURLs() {
var folders, pageToken;
var foldersArray = [["Folder Name", "Link", "Folder ID", "Filepath"]]
do {
try {
var optionalArgs = {
supportsAllDrives: true,
includeItemsFromAllDrives: true,
pageToken: pageToken,
maxResults: 100,
q: '"132vqY8oyd6xKpnxxxxxxxxxxx" in parents and trashed = false and mimeType = "application/vnd.google-apps.folder"'
}
var folders = Drive.Files.list(optionalArgs);
var allFolders = folders.items
if (!allFolders || allFolders.length === 0) {
Logger.log ('No folders found.');
return
}
for (i = 0; i < allFolders.length; i++) {
var folder = allFolders[i];
var name = folder.title
var link = folder.alternateLink
var id = folder.id
var parentID = Drive.Files.get(folder.id,{
supportsAllDrives: true,
}).parents[0].id
var parent = Drive.Files.get(parentID,{
supportsAllDrives: true,
includesItemsFromAllDrives: true,
}).title
var filepath = `${parent}/${name}`
foldersArray.push([name, link, id, filepath])
}
pageToken = folders.nextPageToken;
} catch (err) {
Logger.log('Failed with error %s', err.message);
}
}
while (pageToken);
var ss = SpreadsheetApp.create('Clients Folder ID Listing');
var sheet = ss.getActiveSheet();
sheet.getRange(1,1,foldersArray.length, 4).setValues(foldersArray)
Logger.log(foldersArray)
}
I believe your goal is as follows.
You want to retrieve the folder list in the specific folder.
The specific folder has multiple subfolders.
You want to achieve this using Google Apps Script.
When I saw your script, Drive.Files.get is used in a loop. In this case, the process cost might be high. And, in your script, it seems that the subfolders cannot be retrieved.
In this case, how about the following sample script? In this answer, I used a Google Apps Script library for retrieving the file and folder list using Google Apps Script. I created this library for like this situation.
Usage:
1. Install library.
Please install the Google Apps Script library. You can see the method for installing it at here.
2. Enable Drive API.
This script uses Drive API. So, please enable Drive API at Advanced Google services.
3. Sample script:
function myFunction() {
const folderId = "###"; // Please set the folder ID.
const obj = FilesApp.getAllFoldersInFolder(folderId);
if (obj.id.length == 0) return;
const foldersArray = [["Folder Name", "Link", "Folder ID", "Filepath"], ...obj.name.map((e, i) => {
const folderName = e.pop();
const folderId = obj.id[i].pop();
return [folderName, `https://drive.google.com/drive/folders/${folderId}`, folderId, e.join("/")];
})];
const sheet = SpreadsheetApp.create('Clients Folder ID Listing').getActiveSheet();
sheet.getRange(1, 1, foldersArray.length, 4).setValues(foldersArray);
}
When this script is run, the folder list is retrieved from the specific folder. In this case, the subfolders are included. And, the values of "Folder Name", "Link", "Folder ID", "Filepath" are put into the created Spreadsheet.
In this script, the folder list in the shared drive can be retrieved. When I tested this, I confirmed that a folder list including more than 100 folders could be retrieved.
Reference:
FilesApp: Google Apps Script library.

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 Apps Script: How to trash certain file types from a folder

I have a Google Apps Script that I want to have check a folder (and all subfolders) and set to trashed all files of a certain file type. (in my case Google Doc format files).
I'm certain my problem is with my var filetype or my If statement line. Tried several variations and searched the internet but not finding the answer that helps me.
function trashit() {
var sourcefolder=DriveApp.getFolderById('source folder ID here'); //My Drive folder to take the files from.
var files=sourcefolder.getFiles();
supportsTeamDrives: true;
while(files.hasNext()) { //contintue while statement until all files are run.
var file=files.next();
var filetype=DriveApp.getFilesByType(MimeType.GOOGLE_DOCS);
if (filetype == "GOOGLE_DOCS") { //code does this IF statement when the file type matches
supportsTeamDrives: true;
supportTeamDrives: true;
file.setTrashed(true);
};
}
}
I want this code to check the folder, and set/move to the trash all files of the specified file type. Any help with this would be appreciated.
Try this:
function trashit() {
var sourcefolder=DriveApp.getFolderById('ID');
var files=sourcefolder.getFilesByType(MimeType.GOOGLE_DOCS);
while(files.hasNext()) {
var file=files.next();
file.setTrashed(true);
}
}
I don't believe supportsTeamDrives: true; is used in DriveApp. I believe it is an option in the Advanced Drive API. You should consider taking #webstermath 's advice.

Move file from Drive to TeamDrive folder appscript

I would like to transfer a file from MyDrive to TeamDrive with script from AppmMaker. I use DriveApp to create the file in MyDrive and with a DrivePicker widget from appmaker i get id from target folder to save the file.
DriveApp can move file in TeamDrive with
var file = DriveApp.getFileById(fileId);
var parentFolder = DriveApp.getFolderById(TEAM_DRIVE_ID);
parentFolder.addFile(file);
but not in a folders in TeamDrive.
I have try to use this code :
function moveFileToFolder(fileIds, newFolderId) {
var file = Drive.Files.get(fileIds, {supportTeamDrives: true,supportsTeamDrives: true});
Drive.Files.patch(file, fileIds, {
removeParents: file.parents.map(function(f) { return f.id; }),
addParents: [newFolderId],
supportTeamDrives: true,
supportsTeamDrives: true
});
}
I have the error "Sharing restrictions cannot be set on a Team Drive item."
Reference :How to move a file from MyDrive to Team Drive?
(the solution of the reference not work because i want to move it in a folder in teamdrive not directly in teamdrive)
Any Idea ?
There is a parameter to change in the file metadata because Drive file and Team Drive file are not the same. You can change it with
var file = Drive.Files.get(FileId);
file.capabilities.canMoveTeamDriveItem = true;
And after simply move it with
var fileDriveApp = DriveApp.getFileById(FileId);
fileDriveApp.getParents().next().removeFile(fileDriveApp);
var folder = DriveApp.getFolderById(foldersId);
folder.addFile(fileDriveApp);
Reference : https://developers.google.com/drive/api/v3/reference/files

How to copy google drive folder into another google drive account by using App Script?

I want to copy google drive folder to another google Drive by using App Script. Right now I am sharing folder to target account and try to copy folder to target google drive.Here is my App Script Code:
// Make copy in Google Drive
function CopyTamplate(companyName) {
var folder = DriveApp.getFolderById("<<folder_id>>");
var folderid = folder.getId();
folder.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.VIEW);
Drive.Permissions.insert(
{
'role': 'reader',
'type': 'user',
'value': "target_email#gmail.com"
},
folderid,
{
'sendNotificationEmails': 'false'
});
var sourceFolder = "Company1_copy_tamplete";
var targetFolder = companyName;
var source = DriveApp.getFoldersByName(sourceFolder);
var target = DriveApp.createFolder(targetFolder);
if (source.hasNext()) {
copyFolder(source.next(), target);
}
}
This is a Code for Share folder from One Drive to another by Target Email, Here is a function copyFolder:
function copyFolder(source, target) {
var folders = source.getFolders();
var files = source.getFiles();
while(files.hasNext()) {
var file = files.next();
file.makeCopy(file.getName(), target);
}
while(folders.hasNext()) {
var subFolder = folders.next();
var folderName = subFolder.getName();
var targetFolder = target.createFolder(folderName);
copyFolder(subFolder, targetFolder);
}
}
I have used Google Script Execution API for calling this Script function, and i am getting this Error.
Script error message: "Action not allowed". Please help me to solve the issue or suggest another way to perform this task. Thank you.
This is happening because the role you specified in Drive.Permissions.insert is 'role': 'reader'. Reading the Sharing Files docs, these are the only permitted operations for 'reader':
-Read the metadata (e.g. name, description) of the file or folder
-Read the content of the file
-Read the list of items in the folder
I suggest setting the role to owner or writer instead.