I have a Google Shared Drive with the company I work for (note that this is different than shared folders that come up in Shared With Me - no one person owns the Shared Drive, a team owns/manages it).
I'd like to have script that exists within the Shared Drive and has access to the Shared Drive (ie the scope is within the Shared Drive). DriveApp, by default, has the scope of the creator's My Drive as far as I understand. So I can create a script saved within the Shared Drive but DriveApp is still only within the scope of My Drive.
This code
var rootFolder = DriveApp.getRootFolder();
console.log("Root Folder:", rootFolder.getName());
always returns Root Folder: My Drive
Is there a way to specify which Drive the DriveApp runs as? I.e. get the above code to return Root Folder: Shared Drive Name
In the current stage, unfortunately, DriveApp.getRootFolder() returns the root folder of own Google Drive. So in order to retrieve the root folder of the shared Drive, I would like to propose the following script.
Sample script:
If the shared Drive is only one, how about the following sample script? When you use this, please enable Drive API at Advanced Google services. In this script, the drive ID and name of the shared Drive are retrieved using the method of "Drives: list" in Drive API.
var drive = Drive.Drives.list().items[0];
var rootFolder = DriveApp.getFolderById(drive.id);
console.log("Root Folder:", drive.name);
// When you want to retrieve the files, you can also use the following script.
var files = rootFolder.getFiles();
while (files.hasNext()) {
console.log(files.next().getName())
}
Note:
From June 1, 2020, Drive service like DriveApp got to be able to use the shared Drive. But in the current stage, it seems that all functions cannot be used for the shared Drive. I believe that these might be able to be resolved in the future update.
For example, in the current stage, when above script is used, unfortunately, rootFolder.getName() is not the name of shared Drive. In my environment, it's Drive. So I used drive.name.
References:
Advanced Google services
Drives: list
Related
I'm trying to get folder and file permissions which is located in Shared Drive. All I can get is permissions list for root Shared Drive but trying to run below code on any ID of file or folder inside throw error.
Relavant Facts
We are using Google Workspace Business Plus subscription
I am domain superadmin
I have access to this file in Shared Drive but I expect to have access to every file as an domain admin.
Right now I'm calling the below script from web IDE of Apps Script so it is working in my grant scope.
I am the script owner
Script is on My rive
Script
function getPermissions_(driveFileID, sharedDriveSupport){
var thisDrivePermissions = Drive.Permissions.list(
driveFileID,
{
useDomainAdminAccess: USE_DOMAIN_ADMIN_ACCESS,
supportsAllDrives: sharedDriveSupport
}
);
return thisDrivePermissions;
}
Errors
GoogleJsonResponseException: API call to drive.permissions.list failed with error: Shared drive not found: xxxxxxxx
GoogleJsonResponseException: API call to drive.permissions.list failed with error: File not found:
How can I get the file permissions list in Google Shared Drive with Apps Script?
As superadminin you don't have access to all files by default through Google Drive user interface / Google Apps Script. In order to get access to all files in your domain throught Apps Script you have to make use of domain-wide deletegation of authority.
The "not found" errors might occur because the file or shared drive ids are wrong or you don't have access, do double check that the ids are correct and that you passing the parameters correctly. For this you could use Logger.log
/ console.log to print the variable values to the execution log or use the Apps Script debugger.
Related
How to add a Google Drive folder to "My Drive" section to other users
Take ownership of other users Drive-files using Google Apps Script
If I understand correctly, you need to list all the permissions that a drive file contained in a folder from a shared drive has. To do that, you may check the following script as an example:
function myFunction() {
var driveFileID = "FILE ID";
var sharedDriveSupport = true;
var request = {
"supportsAllDrives": sharedDriveSupport,
"useDomainAdminAccess": true,
"fields": "permissionIds"
};
var permissionsRequest = {
"supportsAllDrives": sharedDriveSupport,
"fields": "role"
};
var permissionsIDs = Drive.Files.get(driveFileID, request);
for(var i=0; i<permissionsIDs.permissionIds.length; i++)
{
Logger.log((Drive.Permissions.get(driveFileID, permissionsIDs.permissionIds[i], permissionsRequest)).role);
}
}
This is how it would display the information, by listing all the permission types from the specified file:
Note that this works because you mentioned you have access to the shared drive, however as Rubén mentioned in his answer Google Workspace admins do not have access to all the files, just to the ones that are shared with them, and if you want to have access you can do it using domain wide delegation and user impersonation.
References:
Files: get
Permissions: get
Question:
I have two Google Shared Drives (Team Drives), let's say Movies and MoviesBackup. I need to backup whatever I upload to Movies into MoviesBackup. For this, I need an unidirectional sync from Movies to MoviesBackup, once daily.
What I have tried:
I know of of Rclone, and have used its Command Line Interface to sync between two Shared Drives. Maybe if Rclone can be used from Google AppScript, I would set a daily trigger. But I seem to find no way to do so.
Any other solutions that work will be appreciated.
Although I'm not sure whether this is the direct solution of your issue, in your situation, how about the following sample script? This sample scripts uses a Google Apps Script library. Ref
When this library is used, a source folder can be copied to the specific destination folder. And, when the files in the source folder are updated, the updated files are copied to the destination folder as the overwrite.
Usage:
1. Install library.
Please install the library to your Google Apps Script project. The method of installing it can be seen at here.
2. Sample script.
Please copy and paste the following script to the script editor of your Google Apps Script project. And save it. And, in this library, Drive API is used. So please enable Drive API at Advanced Google services.
And, please set the source and destination folder IDs to the following object.
function myFunction() {
const object = {
sourceFolderId: "###", // Please set the source folder ID.
destinationFolderId: "###", // Please set the destination folder ID.
overwrite: true,
};
const res = CopyFolder.copyAllFilesFolders(object);
console.log(res);
}
Note:
When this script is run for the 1st time, all files are copied. And, after the script is run as 2 times, only the updated files are copied.
Reference:
CopyFolder of Google Apps Script library
Like I said on the title, I would like to run a Google apps script linked to a google spreadsheet only if the Spreadsheet is located on the user's drive because I work with Spreadsheet template located on teamdrive and the rule is that the user must make a copy on their local Drive to run the script. So I would like to know if it's possible with the file id for exemple to check if I am in a teamdrive or not ?
Thanks for your answers
With the fileId itself, you cannot know whether it is part of a shared drive or not.
However, you can use DriveApp to obtain the file itself, and most importantly, its permission. In order to check that the file is in a personal drive (and owned by the user issuing the request), you have to make sure the permission is in fact OWNER. You can do this with GAS as follows:
function isInPersonalDrive(fileId) {
var file = DriveApp.getFileById(fileId);
return file.getAccess(Session.getActiveUser()) === DriveApp.Permission.OWNER;
}
I am having trouble adding files to the shared google drive folder as well as not being able to remove specific types of files of any kind within my script. The shared google drive file gives me issues. The code below works for me on my own personal google drive folder for adding and removing CSV's from one google drive folder to any another that I specify. However, it does not work with our general shared google drive folder. I have been authorized permission via the google cloud console API for Drive & Sheets but I am still having permission issues. Any help or clarification on this issue would be greatly appreciated.
Here are two different pieces of code. The first one with function moveFiles() works on my personal drive but not in the shared folders. Here is also some more code that I was playing around with to test the shared folders in a simpler manner. I was able to get the putFile() function to put a newDoc inside a shared google drive folder but not able to remove it.
function moveFiles(source_folder, dest_folder)
{
// set current destination to grab the folder from
var currentFolder=DriveApp.getFolderById("1emSsRay_WI_z_qBUpQIoccxQID28FvB0");
// grab only the csv's within current folder
var docs = DriveApp.getFilesByType(MimeType.CSV);
// set target destination where we will store old csv's that have been processed & Analyzed
var destination = DriveApp.getFolderById("1wYG1Gd5z0-nucedSMOBn8ZJs68ZgR8Hb");
// iterate through the csv's files within the currentFolder, add them to the destination and remove them from the current folder
while (docs.hasNext())
{
var doc = docs.next();
destination.addFile(doc); // get error "Cannot use this operation on a shared drive item(line 13, file "SharedDriveMove")
currentFolder.removeFile(doc);
}
}
function putFile()
{
var newDoc = DocumentApp.create('Testing Team Drive MoveTo').getId();
var file = DriveApp.getFileById(newDoc);
var moveFile = DriveApp.getFolderById('1emSsRay_WI_z_qBUpQIoccxQID28FvB0').addFile(file);
}
function takeFile()
{
var filesIterator = DriveApp.getFilesByName('Testing Team Drive MoveTo');
while (filesIterator.hasNext())
{
var file = filesIterator.next();
}
var cleanup = DriveApp.getFolderById('1wYG1Gd5z0-nucedSMOBn8ZJs68ZgR8Hb').addFile(file,{"supportsAllDrives": true}); // get error "Cannot find method addFile(File,Object).(line 15,file"Code")
var moveFile = DriveApp.getFolderById('1emSsRay_WI_z_qBUpQIoccxQID28FvB0').removeFile(file,{"supportsAllDrives": true});
}
DriveApp is an Apps Script class whereby it has it's limitations among Drive. Also, as the documentation says:
This method does not delete the file, but if a file is removed from
all of its parents, it cannot be seen in Drive except by searching for
it or using the "All items" view.
You should do it with the Drive API instead:
Use "supportsAllDrives", otherwise it won't find the file if it's in a Shared Drive (until this is deprecated in 2020).
Drive.Files.remove("your file ID", {"supportsAllDrives": true});
You also have to authorize the Drive.File scope.
I am creating a few forms using Google Apps Script which automatically generates in my root (My Drive) of my Google Drive.
I want to move these forms to a specific folder of a Shared Drive.
I googled about moving files (or any object) to another folder, most of them are suggesting that copy the file to a specific location, then delete from the source location.
But in this case, my formIds are changing which I don't want to change.
Is there any better way to move files (in my case Forms) to another location in Google Drive?
As a developer you should always favor canonical sources over 3rd party tutorials that pop-up in google search. The official documentation for the Drive API has guides describing how to move files from one drive folder to the next. I suggest you start there.
the following code should work for moving any file, including forms, to a destination folder in Google Drive:
var fileId = '1234567890abcdefghijklmnopqrstuvwxyz'; //<--replace string with your file ID
var destinationFolderId = 'zyxwvutsrqponmlkjihgfedcba0987654321';//<--replace string with your destination folder ID
function moveFile(fileId,destinationFolderId) {
var destinationFolder = DriveApp.getFolderById(destinationFolderId);
DriveApp.getFileById(fileId).moveTo(destinationFolder);
}