3

I have the following (mostly) working script using the Admin Directory API. However, rather than pulling the entire domain - I would like to just pull the information for a specific department.

function listAllUsers() {
  var ss = SpreadsheetApp.getActive();
  var pageToken, page, count = 0;
  var listArray = [];
  listArray.push(['full name', 'first name', 'last name', 'email', 'department', 'ID'])
  do {
    page = AdminDirectory.Users.list({
      domain: 'example.co.uk',
      orderBy: 'givenName',
      maxResults: 100,
      pageToken: pageToken
    });
    var users = page.users;
    if (users) {
      for (var i = 0; i < users.length; i++) {
        var user = users[i];
        listArray.push([user.name.fullName, user.name.givenName, user.name.familyName, user.primaryEmail, user.organizations, user.id,]);
      }
    }
    pageToken = page.nextPageToken;
    break; // This means you only get one page
  } while (pageToken);
  try {
    var outputSheet = ss.getSheetByName('allMembers');
    outputSheet.getDataRange();
  } catch(err) {
    var outputSheet = ss.insertSheet('allMembers', 2);
  }
  outputSheet.getDataRange().clear();
  outputSheet.getRange(1, 1, listArray.length, listArray[0].length).setValues(listArray);
  outputSheet.getRange(1, 6, outputSheet.getLastRow(), 4).setHorizontalAlignment("center");
  outputSheet.getRange(1, 1, outputSheet.getLastRow(), 1).setHorizontalAlignment("center");
  var width = [150, 150, 180, 250, 250, 200];
  formatSheet(outputSheet, width);
}

I have tried to filter to the domain by using user.organization[].domain but just got error messages. I changed the parameter user.organizations to user.organizations[].department as documented in the Admin SDK reference.

This initially threw out a SyntaxError, and when changed to user.organizations[0].department it threw out the error message:

TypeError: Cannot read property "0" from undefined

I omitted the brackets altogether and used user.organizations.department, but got:

TypeError: Cannot read property "department" from undefined

Also, if possible I would like to list the Department and Title separably. Currently, it exports the information in this format:

{customType=work, name=, location=002, title=Technical Support Manager, department=Technical Support, primary=true}

The current display:
Here is a screenshot of how the information is displayed in a Google Sheet

My desired output format:
Here is a screenshot of how I would like it to appear

tehhowch
  • 9,645
  • 4
  • 24
  • 42
Moonie
  • 33
  • 1
  • 5
  • If you tried to do it one way and get error messages, would it not make sense to share said code and said error messages? Have you tried a different query? Also, your department and title are already separate values, so I'm not sure what you are having difficulty with. – tehhowch Apr 06 '18 at 12:19
  • Have updated the post to show what I have tried and give some screenshots to explain things a little better. – Moonie Apr 06 '18 at 12:45

2 Answers2

2

You are getting those errors because some of the users in your domain don't have the department/ title user property.

Adding 2 variable and try.. catch blocks should allow the code to work as you expect.

Here is the updated code:

function listAllUsers() {
    var ss = SpreadsheetApp.getActive();
    var pageToken,
    page,
    count = 0;
    var listArray = [];
    listArray.push(['full name', 'first name', 'last name', 'email', 'department', 'title', 'ID'])
    do {
        page = AdminDirectory.Users.list({
                domain : 'example.com',
                orderBy : 'givenName',
                pageToken : pageToken
            });
        var users = page.users;
        if (users) {
            for (var i = 0; i < users.length; i++) {
                var user = users[i];
                var department,
                title; // Addded two new variables 
                try { // Try to get the users department if there is an error push the error to the array
                    department = user.organizations[0].department;
                } catch (e) {
                    department = e
                }
                try {// Try to get the users title if there is an error push the error to the array
                    title = user.organizations[0].title;
                } catch (e) {
                    title = e
                }
                listArray.push([user.name.fullName, user.name.givenName, user.name.familyName, user.primaryEmail, department, title, user.id, ]);

            }
        }
        pageToken = page.nextPageToken;
        break; // This means you only get one page
    } while (pageToken);
    try {
        var outputSheet = ss.getSheetByName('allMembers');
        outputSheet.getDataRange();
    } catch (err) {
        var outputSheet = ss.insertSheet('allMembers', 2);
    }
    outputSheet.getDataRange().clear();
    outputSheet.getRange(1, 1, listArray.length, listArray[0].length).setValues(listArray);
    outputSheet.getRange(1, 6, outputSheet.getLastRow(), 4).setHorizontalAlignment("center");
    outputSheet.getRange(1, 1, outputSheet.getLastRow(), 1).setHorizontalAlignment("center");
    var width = [150, 150, 180, 250, 250, 200];
    formatSheet(outputSheet, width);
}

UPDATE

To only list the users in a certain department you would just need to add a if around the push

 if(department == '--NAME OF DEPARTMENT--'){
      listArray.push([user.name.fullName, user.name.givenName, user.name.familyName, user.primaryEmail, department, title, user.id,]);
   }
James D
  • 3,102
  • 1
  • 11
  • 21
  • Thanks James, I will take a look at this. I was using the Directory API documentation (which is working for the other values I am trying to look up). – Moonie Apr 06 '18 at 12:47
  • Sorry, the Users | Directory API documentation. – Moonie Apr 06 '18 at 12:52
  • Ya, the documentation is quite scattered. If it doesn't work post back and let us know, I'll set up the fields and test them on my domain. – James D Apr 06 '18 at 12:52
  • Doesn't look like we are using those fields. Just comes back as undefined. We use GADs to sync from AD into G Suite, which is where it is pulling the Department information from. – Moonie Apr 06 '18 at 13:24
  • Even I am facing same problem -- any solutions I am using "user.organizations[0].department o and user.organizations[0].title" – KiKu Apr 10 '18 at 10:00
  • @Moonie Please see my updated answer, this should do the trick. – James D Apr 10 '18 at 13:15
  • @JamesD I never even thought of that! Fantastic. You're a star! – Moonie Apr 13 '18 at 07:44
  • @JamesD Anyway you are aware of to restrict it pulling people that match a certain criteria? Like just a certain department? – Moonie Apr 13 '18 at 11:08
0

Using admin SDK and query you can search user on the basis of attributes like OrgName, ManagerId, Ref Linkenter link description here. Pass query in your request

     var queryStr="orgDepartment=HR"
     var page = AdminDirectory.Users.list({
                    domain : 'example.com',
                    orderBy : 'givenName',
                    pageToken : pageToken,
                    query:queryStr
                });
Shivaji
  • 367
  • 3
  • 5