Search code examples
google-admin-sdkgoogle-workspacegoogle-directory-api

Directory API - How to use pageToken in Users List


Using Google App Script with GSuite's Directory API. I want to list all users from the root OU. This code pulls all users from the directory and filters out those who are members of sub-OU.

The code.

/**
* LIST USERS FROM ROOT OU
*/
function listUsers() {
var optionalArgs = {
domain: 'mydomain.com',
maxResults: 500,
orderBy: 'givenName'
};
var response = AdminDirectory.Users.list(optionalArgs);
var users = response.users;
var counter = 0;
if (users && users.length > 0) {
Logger.log('Liste des utilisateurs...\n');
for (i = 0; i < users.length; i++) {
  var user = users[i];
  /* FILTER OUT SUB-OU, PRINT ONLY MEMBERS IN ROOT OU */
  if (user.orgUnitPath == '/') {
    counter++;
    Logger.log('Result #%s', counter.toString());
    Logger.log('\nName : %s\nEmail : %s\nOU : %s\n', user.name.fullName, user.primaryEmail, user.orgUnitPath);
    }
}
} else {
Logger.log('Nothing found...');
}
}

Now the function listUsers has a cap of 500 results but my organisation has way more users accounts.

I know my problem will be solved by the use of the pageToken parameter and this has been asked time and again. I have been reading through many posts on the subject, and yet, I am not finding any clear explanation and a way to adapt this to App Script.

Any help would be greatly appreciated.


Solution

  • I figured it out

    function listUsers(){
      var values = [],
      users = [],
      userListQuery = {},
      nextPageToken = '',
      listObject = {
        customer: 'my_customer',
        query: "isSuspended=false",
        maxResults: 500
      },
      i = 0,
      j = 0;
    
    do {
    
    if (nextPageToken && nextPageToken !== '') {
      listObject.pageToken = nextPageToken;
    }  
    
    var userListQuery = AdminDirectory.Users.list(listObject);
    
    // Si plus de maxResults retourner à nextPageToken
    nextPageToken = userListQuery.nextPageToken;
    
    // Ajout de résultats à la liste
    users = users.concat(userListQuery.users);
    
    } while (nextPageToken);
    
    for (i = 0; i < users.length; i++) {
    // Filtrer les résultats
    if (users[i].orgUnitPath == '/') {
      j++;
      Logger.log('Résultat #%s', j.toString());
      Logger.log('\nNom : %s\nCourriel : %s\nOU : %s\nDépartement : %s\n', users[i].name.fullName, users[i].primaryEmail, users[i].orgUnitPath, users[i].orgDepartment);
      }
     }
    }