Google Device Deletion using Google App Script

61 Views Asked by At

Does anyone have experience deleting the device in Google using Google App Script? We want to delete the device which is not synced within 60 days.

The reason we need to create a script is that we don't want to delete the device manually through the Google Admin Console.

Thank you.

function deleteInactiveDevices() {
  // Define the number of days after which a device is considered inactive
  const SYNC_THRESHOLD_DAYS = 100;

  // Get the Admin Directory Service
  const admin = AdminDirectory.Devices;

  // Get all devices
  const devices = admin.list();

  // Loop through devices
  while (devices.items) {
    devices.items.forEach(function(device) {
      if (!device.lastSyncTime) {
        // No last sync time available, skip device
        return;
      }

      // Calculate days since last sync
      const daysSinceLastSync = Math.floor((Date.now() - new Date(device.lastSyncTime)) / 1000 / 60 / 60 / 24);

      if (daysSinceLastSync > SYNC_THRESHOLD_DAYS) {
        // Device is inactive, delete it
        console.log(`Deleting inactive device: ${device.name}`);
        admin.delete(device.deviceId);
      }
    });

    // Get next page of devices
    devices = devices.nextPageToken ? admin.list({ pageToken: devices.nextPageToken }) : null;
  }
}

Tried the above script but return with error: TypeError: Cannot read properties of undefined (reading 'list') deleteInactiveDevices @ Code.gs:9

0

There are 0 best solutions below