Manage shared drives

Much of the information you'll need to get started creating and managing shared drives is detailed in the shared drives reference. Here are a few more important considerations when working with shared drives.

Create shared drives

Use drives.create to create a new shared drive.

Java

Drive driveMetadata = new Drive();
driveMetadata.setName("Project Resources");
String requestId = UUID.randomUUID().toString();
Drive drive = driveService.drives().create(requestId,
    driveMetadata)
    .execute();
System.out.println("Drive ID: " + drive.getId());

Python

drive_metadata = {'name': 'Project Resources'}
request_id = str(uuid.uuid4())
drive = drive_service.drives().create(body=drive_metadata,
                                               requestId=request_id,
                                               fields='id').execute()
print 'Drive ID: %s' % drive.get('id')

PHP

$driveMetadata = new Google_Service_Drive_Drive(array(
    'name' => 'Project Resources'));
$requestId = Uuid::uuid4()->toString();
$drive = $driveService->drives->create($requestId, $driveMetadata, array(
    'fields' => 'id'));
printf("Drive ID: %s\n", $drive->id);

.NET

var driveMetadata = new Drive()
{
    Name = "Project Resources"
};
var requestId = System.Guid.NewGuid().ToString();
var request = driveService.Drives.Create(driveMetadata, requestId);
request.Fields = "id";
var drive = request.Execute();
Console.WriteLine("Drive ID: " + drive.Id);

Ruby

drive_metadata = {
    name: 'Project Resources'
}
request_id = SecureRandom.uuid
drive = drive_service.create_drive(request_id,
                                            drive_metadata,
                                            fields: 'id')
puts "Drive Id: #{drive.id}"

Node.js

var driveMetadata = {
  'name': 'Project resources'
};
var requestId = uuid.v4();
driveService.drives.create({
  resource: driveMetadata,
  requestId: requestId,
  fields: 'id'
}, function (err, drive) {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    console.log('Drive Id: ', drive.id);
  }
});

Calls to drives.create are idempotent. The requestId parameter identifies the logical attempt to create the shared drive. If the request times out or returns an indeterminate backend error, the same request may be repeated. The requestId and body of the request must remain the same.

If the shared drive was successfully created on a previous request or as a result of a retry, the normal response is returned. In some cases, such as after a prolonged period of time or if the body of the request has changed, a 409 error may be returned indicating the requestId must be discarded.

Manage members and permissions

Add or remove members of a shared drive using the permissions collection.

To add a member, create the permission on the shared drive itself. Permission methods can also be used on individual files within a shared drive to grant members additional privileges or allow non-members to collaborate on specific items.

See Share files and folders for additional details and sample code.

Delete shared drives

Use the drives.delete method to remove a shared drive. All content in the shared drive must be trashed or deleted prior to deleting the shared drive.

Manage shared drives for domain administrators

Use the useDomainAdminAccess parameter with the drives and permissions resources to manage shared drives across an organization.

Users calling these methods with useDomainAdminAccess=true must have the Drive and Docs administrator privilege. Administrators can search for shared drives or update permissions for shared drives owned by their organization, regardless of the admin's membership in any given shared drive.

The following example demonstrates how to use these resources to recover shared drives that no longer have an organizer.

Java

// Find all shared drives without an organizer and add one.
// Note: This example does not capture all cases. Shared drives
// that have an empty group as the sole organizer, or an
// organizer outside the organization are not captured. A
// more exhaustive approach would evaluate each shared drive
// and the associated permissions and groups to ensure an active
// organizer is assigned.
String pageToken = null;
Permission newOrganizerPermission = new Permission()
    .setType("user")
    .setRole("organizer")
    .setEmailAddress("user@example.com");

do {
  DriveList result = driveService.drives().list()
      .setQ("organizerCount = 0")
      .setFields("nextPageToken, drives(id, name)")
      .setUseDomainAdminAccess(true)
      .setPageToken(pageToken)
      .execute();
  for (Drive drive : result.getDrives()) {
    System.out.printf("Found drive without organizer: %s (%s)\n",
        drive.getName(), drive.getId());
    // Note: For improved efficiency, consider batching
    // permission insert requests
    Permission permissionResult = driveService.permissions()
        .create(drive.getId(), newOrganizerPermission)
        .setUseDomainAdminAccess(true)
        .setSupportsAllDrives(true)
        .setFields("id")
        .execute();
    System.out.printf("Added organizer permission: %s\n",
        permissionResult.getId());

  }
  pageToken = result.getNextPageToken();
} while (pageToken != null);

Python

# Find all shared drives without an organizer and add one.
# Note: This example does not capture all cases. Shared drives
# that have an empty group as the sole organizer, or an
# organizer outside the organization are not captured. A
# more exhaustive approach would evaluate each shared drive
# and the associated permissions and groups to ensure an active
# organizer is assigned.
page_token = None
new_organizer_permission = {
    'type': 'user',
    'role': 'organizer',
    'emailAddress': 'user@example.com'
}

while True:
    response = drive_service.drives().list(
            q='organizerCount = 0',
            fields='nextPageToken, drives(id, name)',
            useDomainAdminAccess = True,
            pageToken=page_token).execute()
    for drive in response.get('drives', []):
        print 'Found shared drive without organizer: %s (%s)' % (
            drive.get('title'), drive.get('id'))
        permission = drive_service.permissions().create(
                fileId=drive.get('id'),
                body=new_organizer_permission,
                useDomainAdminAccess = True,
                supportsAllDrives = True,
                fields='id').execute()
        print 'Added organizer permission: %s ' % (permission.get('id'))

    page_token = response.get('nextPageToken', None)
    if page_token is None:
        break

PHP

// Find all shared drives without an organizer and add one.
// Note: This example does not capture all cases. Shared drives
// that have an empty group as the sole organizer, or an
// organizer outside the organization are not captured. A
// more exhaustive approach would evaluate each shared drive
// and the associated permissions and groups to ensure an active
// organizer is assigned.
$pageToken = null;
$newOrganizerPermission = new Google_Service_Drive_Permission(array(
    'type' => 'user',
    'role' => 'organizer',
    'emailAddress' => 'user@example.com'
));

do {
    $response = $driveService->drives->listDrives(array(
        'q' => 'organizerCount = 0',
        'fields' => 'nextPageToken, drives(id, name)',
        'useDomainAdminAccess' => true,
        'pageToken' => $pageToken
    ));
    foreach ($response->drives as $drive) {
        printf("Found shared drive without organizer: %s (%s)\n",
            $drive->name, $drive->id);
        $permission = $driveService->permissions->create($drive->id,
            $newOrganizerPermission,
            array(
                'fields' => 'id',
                'useDomainAdminAccess' => true,
                'supportsAllDrives' => true
            ));
        printf("Added organizer permission: %s\n", $permission->id);
    }
    $pageToken = $repsonse->pageToken;
} while ($pageToken != null);

.NET

// Find all shared drives without an organizer and add one.
// Note: This example does not capture all cases. Shared drives
// that have an empty group as the sole organizer, or an
// organizer outside the organization are not captured. A
// more exhaustive approach would evaluate each shared drive
// and the associated permissions and groups to ensure an active
// organizer is assigned.
string pageToken = null;
var newOrganizerPermission = new Permission()
{
    Type = "user",
    Role = "organizer",
    EmailAddress = "user@example.com"
};

do
{
    var request = driveService.Drives.List();
    request.UseDomainAdminAccess = true;
    request.Q = "organizerCount = 0";
    request.Fields = "nextPageToken, drives(id, name)";
    request.PageToken = pageToken;
    var result = request.Execute();
    foreach (var drive in result.Drives)
    {
        Console.WriteLine(string.Format(
               "Found abandoned shared drive: {0} ({1})",
               drive.Name, drive.Id));
        // Note: For improved efficiency, consider batching
        // permission insert requests
        var permissionRequest = driveService.Permissions.Create(
          newOrganizerPermission,
          drive.Id
        );
        permissionRequest.UseDomainAdminAccess = true;
        permissionRequest.SupportsAllDrives = true;
        permissionRequest.Fields = "id";
        var permissionResult = permissionRequest.Execute();
        Console.WriteLine(string.Format(
               "Added organizer permission: {0}", permissionResult.Id));

    }
    pageToken = result.NextPageToken;
} while (pageToken != null);

Ruby

# Find all shared drives without an organizer and add one.
# Note: This example does not capture all cases. Shared drives
# that have an empty group as the sole organizer, or an
# organizer outside the organization are not captured. A
# more exhaustive approach would evaluate each shared drive
# and the associated permissions and groups to ensure an active
# organizer is assigned.
new_organizer_permission = {
    type: 'user',
    role: 'organizer',
    email_address: 'user@example.com'
}

drives = drive_service.fetch_all(items: :drives) do |page_token|
  drive_service.list_drives(
      q: 'organizerCount = 0',
      fields: 'nextPageToken, drives(id, name)',
      use_domain_admin_access: true,
      page_token: page_token)
end

for drive in drives
  puts "Found shared drive without organizer: #{drive.name} #{drive.id}"
  permission = drive_service.create_permission(drive.id,
                                               new_organizer_permission,
                                               use_domain_admin_access: true,
                                               supports_all_drives: true,
                                               fields: 'id')
  puts "Added organizer permission: {permission.id}"
end

Node.js

var newOrganizerPermission = {
  type: 'user',
  role: 'organizer',
  emailAddress: 'user@example.com'
};

var pageToken;
// Using the npm module 'async'
async.doWhilst(function (callback) {
  driveService.drives.list({
    q: "organizerCount = 0",
    fields: 'nextPageToken, drives(id, name)',
    useDomainAdminAccess: true,
    pageToken: pageToken
  }, function (err, res) {
    if (err) {
      // Handle error
      console.error(err);
      callback(err)
    } else {
      async.eachSeries(res.drives, function (drive, callback) {
        console.log('Found shared drive without organizer:',
            drive.name, drive.id);
        driveService.permissions.create({
          resource: newOrganizerPermission,
          fileId: drive.id,
          useDomainAdminAccess: true,
          supportsAllDrives: true,
          fields: 'id'
        }, callback);
      }, callback);
      pageToken = res.nextPageToken;
    }
  });
}, function () {
  return !!pageToken;
}, function (err) {
  if (err) {
    // Handle error
    console.error(err);
  } else {
    // All pages fetched
  }
});

Additional considerations when you create and manage shared drives

When searching for shared drives with the drives.list to audit shared drives, consider the following statements.

  1. A shared drive with an organizerCount of zero can only be managed by an administrator.
  2. A shared drive with a memberCount of zero can only be accessed by an administrator.
  3. A shared drive with an organizerCount or memberCount greater than zero may still only be accessed by an administrator if the remaining permissions are for empty groups, or external users that were added prior to disabling sharing outside the domain.
  4. The organizerCount and memberCount fields do not distinguish between members of the organization and external members.
  5. Files inside a shared drive with a memberCount of zero can still be accessed by entities written on the file permission.

傳送您對下列選項的寶貴意見...

這個網頁
Drive REST API
Drive REST API
需要協助嗎?請前往我們的支援網頁