List All Users of a Google Workspace Domain in Google Sheets
The enterprise editions of Google Drive Auditor and Gmail Address Extractor use the Google Apps Admin SDK (Directory API) with Google Apps Script to create a list of all users that are part of a Google Workspace domain.
The Google Scripts gets the name and email address of users in the organization and saves the list inside a Google Spreadsheet. This script can only be executed by the domain administrator.
function getDomainUsersList() {
var users = [];
var options = {
domain: 'ctrlq.org', // Google Workspace domain name
customer: 'my_customer',
maxResults: 100,
projection: 'basic', // Fetch basic details of users
viewType: 'domain_public',
orderBy: 'email', // Sort results by users
};
do {
var response = AdminDirectory.Users.list(options);
response.users.forEach(function (user) {
users.push([user.name.fullName, user.primaryEmail]);
});
// For domains with many users, the results are paged
if (response.nextPageToken) {
options.pageToken = response.nextPageToken;
}
} while (response.nextPageToken);
// Insert data in a spreadsheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Users') || ss.insertSheet('Users', 1);
sheet.getRange(1, 1, users.length, users[0].length).setValues(users);
}
Remember to replace ctrlq.org
with your own domain address. You will need to enable the Admin Directory API under Resources > Advanced Google Services.
Then go to Resources > Cloud Platform Project
, click the Project name to open the Google Developer console associated with your Apps Script project. Switch to the Library section, search for Admin SDK and enable the API.
Amit Agarwal
Google Developer Expert, Google Cloud Champion
Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India.
Amit has developed several popular Google add-ons including Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory