0

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

3
  • 1
    If the list of mobile devices need to be retrieved, then this line of code: const admin = AdminDirectory.Devices; should be replaced with this line of code: const admin = AdminDirectory.Mobiledevices;, it can be checked, if it works. Commented Jan 8, 2024 at 13:08
  • Hi @Jai thank you, changed the code to AdminDirectory.Mobiledevices, but the return with different error. Exception: Invalid number of arguments provided. Expected 1-2 only deleteInactiveDevices @ Code.gs:9 I believe Google is not supporting device API, so I will close this question as soon as possible :) Commented Jan 9, 2024 at 8:12
  • 1
    This link can be checked: developers.google.com/admin-sdk/directory/reference/rest/v1/…. Commented Jan 9, 2024 at 13:26

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.