Reputation: 35
I'd like to add all users in a child Organization Unit to a group. I can do that in Admin Dashboard but it only shows 50 users at a time. Since we have thousands of users in each child OU, this process would be inconvenience.
My solution: I followed a guide (Source) and used Google Apps Script to run the following code but it simply didn't do anything. The log shows "Execution started" then "Execution completed" but no user is moved to the group. I suspect the format for the OU in the code is wrong. It is a bit tricky to get it right especially the OU is Arabic (Right to Left). Any idea what could be wrong?
function myFunction() {
/**
* Add all users of an organizational unit (OU) to specific groups
* in Google Workspace
*
* Usage:
* Change the OU variable, in a format of /OU/SubOU/SubSubOU. The root OU is represented as /
* Change the groupEmails variable, which is a list of group emails.
*
* © 2021 xFanatical, Inc.
* @license MIT
*
* @since 1.0.0 proof of concept
*/
const OU = '/كلية الطب/الطلبة/طلبة الدراسات الاولية 2019 - 2020/testing'
const groupEmails = ['[email protected]']
function addAllOUUsersToGroup() {
let pageToken
let page
do {
page = AdminDirectory.Users.list({
customer: 'my_customer',
maxResults: 100,
pageToken,
query: `orgUnitPath='${OU}'`,
})
let users = page.users
if (users) {
users.forEach((user) => {
groupEmails.forEach((groupEmail) => {
try {
AdminDirectory.Members.insert({
email: user.primaryEmail,
role: 'MEMBER',
type: 'USER',
}, groupEmail)
Logger.log(`Added user [${user.primaryEmail}] to group [${groupEmail}]`)
} catch (e) {
Logger.log(`Failed to add user [${user.primaryEmail}] to group [${groupEmail}], error: ${e.details && e.details.message && e.details.message}`)
}
})
})
} else {
Logger.log('No users found.')
}
pageToken = page.nextPageToken
} while (pageToken)
}
}
Upvotes: 1
Views: 626
Reputation: 19309
You are not executing the function addAllOUUsersToGroup
.
addAllOUUsersToGroup
is declared inside myFunction
, but it is never called. Therefore, if you execute myFunction
, addAllOUUsersToGroup
won't run.
Either call addAllOUUsersToGroup
inside myFunction
. For example:
function myFunction() {
// ...stuff...
function addAllOUUsersToGroup() {
// ...stuff...
}
addAllOUUsersToGroup(); // <== ADD THIS
}
Or, alternatively, take the function addAllOUUsersToGroup
outside myFunction
and call it directly:
function addAllOUUsersToGroup() { <== THIS IS NOT INSIDE myFunction
// ...stuff...
}
Upvotes: 1