I'm experimenting with Admin SDK and trying to list Group Members in a Google Spreadsheet. Here's the code I've come up with:
function recordGroupsMembers() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Get all groups
var groupPageToken, groupPage;
do {
groupPage = AdminDirectory.Groups.list({
domain: 'mydomain.com',
maxResults: 100,
pageToken: groupPageToken
});
var groups = groupPage.groups;
if (groups) {
//Iterate groups
for (var i in groups) {
var group = groups[i];
//Get members of group
var membersPageToken, membersPage;
do {
membersPage = AdminDirectory.Members.list(group, {
maxResults: 100,
pageToken: membersPageToken
});
var members = membersPage.members;
if (members) {
//Iterate group members
for (var j in members) {
var member = members[j];
Logger.log('%s member: %s', group.email, member.email);
}
} else {
Logger.log('%s: no members.', group.email);
}
membersPageToken = membersPage.nextPageToken;
} while (membersPageToken);
}
} else {
Logger.log('No groups found.');
}
groupPageToken = groupPage.nextPageToken;
} while (groupPageToken);
ScriptProperties.setProperty('lastUpdate', new Date());
}
For the AdminDirectory.Members.list
call, this error is shown:
Not Authorized to access this resource/api
To be clear, the Admin SDK Directory Service has been enabled under Resources > Advanced Google services…, and in the Google Developer Console.
Also, the user running this script is able to successfully retrieve expected results using the API Explorer.
I get the impression I've either overlooked something very simple or there's a bug in the statement that "Apps Script handles the authorization flow automatically".