Find and remove inactive users in your Google Workspace domain

Enable Administrator Directory SDK

You Might Be Interested In

Learn how to find inactive users in your Google Workspace domain and delete inactive accounts to save on your monthly bills.

You can use Google Apps Script to find all inactive user accounts in your Google Workspace domain. The script will find all users who have not logged into the domain for a period of time (eg 6 months). You also have the option to delete inactive accounts from the workspace domain and save on your monthly bills.

Find inactive users in a Google Workspace domain

We can use Apps Script’s admin directory service to list all users (active and inactive) in a Google Workspace domain. Open a new script, go to the Services section and enable the Admin Directory Service.

Next, go to the Google Cloud project associated with your Apps Script project. Switch to the Libraries section, search for Admin SDK and turn on APIs. Required OAuth scope is And it’s yours. should be listed in appsscript.json file.

{ "timeZone": "Asia/Kolkata", "dependencies": { "enabledAdvancedServices": [ { "userSymbol": "AdminDirectory", "version": "directory_v1", "serviceId": "admin" } ] }, "exceptionLogging": "STACKDRIVER", "oauthScopes": [""], "runtimeVersion": "V8" }

Enable Administrator Directory SDK

The script will list all the users in the domain and find the inactive accounts based on the last login date. If a user has not logged into his account in the last 6 months, the user is considered inactive and may be deleted.

const getInactiveAccounts = () => { let accounts = []; let pageToken = null; do { const { users, nextPageToken = null } = AdminDirectory.Users.list({ domain: '', customer: 'my_customer', maxResults: 100, orderBy: 'email', pageToken, }); pageToken = nextPageToken; accounts = [...accounts, ...users]; } while (pageToken !== null); const MONTHS = 6; const cutOffDate = new Date(); cutOffDate.setMonth(cutOffDate.getMonth() - MONTHS); const inactiveAccounts = accounts .filter(({ isAdmin }) => isAdmin === false) .filter(({ lastLoginTime }) => { const lastLoginDate = new Date(lastLoginTime); return lastLoginDate < cutOffDate; }) .const(({ primaryEmail }) => primaryEmail); Logger.log(`We found ${inactiveAccounts.length} inactive accounts in the domain.`); Logger.log(`The list is: ${inactiveAccounts.join(', ')}`); const DELETE_USER = false; if (DELETE_USER) { inactiveAccounts.forEach((userEmail) => { AdminDirectory.Users.remove(userEmail); Logger.log(`Deleted Google Workspace account for ${userEmail}`); }); } };