I am usning this code I found here >https://stackoverflow.com/questions/58161549/how-to-get-access-token-for-admin-directory-userlist-api to retrieve the email addresses of all users in our domain, and it is going into an infinite loop. When I printed the output, the code is printing the same 100 users over and over again when we have over 1500 users.
I tried adding Utilities.sleep(1000);
, up to 20 seconds in different points in my code and still the same results.
function myFunction() {
var loggedUser = Session.getActiveUser().getEmail();
var domain = loggedUser.split('@')[1];
var pageToken;
var emails = [];
do {
var url = 'https://www.googleapis.com/admin/directory/v1/users?domain=' domain;
var options = {
"method": "get",
"pageToken": pageToken,
"muteHttpExceptions": true,
"headers": { "Authorization": "Bearer " ScriptApp.getOAuthToken() },
"contentType": "application/json",
}
var res = UrlFetchApp.fetch(url, options);
Logger.log(res);
var page = JSON.parse(res);
//Logger.log(page);
var users = page.users;
if (users) {
for (var i = 0; i < users.length; i ) {
var user = users[i];
Logger.log(user.primaryEmail);
emails.push(user.primaryEmail);
}
} else {
Logger.log('No users found.');
}
pageToken = page.nextPageToken;
} while (pageToken);
}
This is driving me nuts, I searched everywhere, what am I dping wrong here?
CodePudding user response:
Try this:
function getDomainUserList() {
var users = [];
var options = {
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);
Logger.log(users);
}
This function should consider the next page token and retrieve all users from the domain.