Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save phillypb/021b07e28d9a91a71deed2f8fa0bdedf to your computer and use it in GitHub Desktop.

Select an option

Save phillypb/021b07e28d9a91a71deed2f8fa0bdedf to your computer and use it in GitHub Desktop.
/**
* Create menu item to run code from spreadsheet.
*/
function onOpen() {
SpreadsheetApp.getUi()
.createMenu('Admin')
.addItem('Assign licences', 'assignAILicensesFromSheet')
.addToUi();
};
/**
* Function designed to ADD a Google AI licence to bulk users.
* And ADD each user to a Google Group (only upon successful licence application).
*/
function assignAILicensesFromSheet() {
// fetch all data (email addresses) from the Google Sheet
const sheet = SpreadsheetApp.getActiveSheet();
const data = sheet.getDataRange().getValues();
// create empty array to push email email addresses into once they have been cleansed below
const userEmails = [];
// loop through rows (email addresses)
for (let i = 1; i < data.length; i++) {
// get single email address
const email = data[i][0];
// check the cell is not empty and remove any whitespace
if (email && email.toString().trim() !== "") {
userEmails.push(email.toString().trim());
};
};
// stop if the Google Sheet is empty, to avoid errors
if (userEmails.length === 0) {
console.log("No email addresses found to process. Please check your Google Sheet.");
return;
};
// License Configuration - provide details here
const productId = "ENTER HERE";
const skuId = "ENTER HERE";
const groupEmail = "ENTER HERE";
// create empty arrays for pushing email addresses into depending upon success of process
const skippedUsers = [];
const successfulUsers = [];
const failedUsers = [];
// process the email addresses
userEmails.forEach(email => {
console.log("Email address is: " + email);
try {
// attempt to assign the licence directly
AdminLicenseManager.LicenseAssignments.insert(
{ userId: email },
productId,
skuId
);
successfulUsers.push(email);
// attempt to add them to the Google Group
try {
AdminDirectory.Members.insert(
{
email: email,
role: "MEMBER"
},
groupEmail
);
} catch (groupError) {
// if they are already in the group, it's fine, we can silently ignore it.
// if it's a different error, we log a warning but don't fail the whole user operation.
if (!groupError.message.toLowerCase().includes("already exists")) {
console.log(`Warning: License applied for ${email}, but failed to add to group. Reason: ${groupError.message}`);
};
};
} catch (error) {
const errorMessage = error.message.toLowerCase();
// catch users who already have the exact licence
if (errorMessage.includes("already has a license")) {
skippedUsers.push(email);
} else {
// catch actual failures (e.g., typos in emails, out of licences, etc.)
failedUsers.push({ email: email, reason: error.message });
};
};
});
// console logging
console.log("=== LICENCE ASSIGNMENT SUMMARY ===");
console.log(`Successfully assigned licences (and added to group) for ${successfulUsers.length} user(s).`);
if (successfulUsers.length > 0) console.log("Successful Users:", successfulUsers);
console.log(`\nSkipped ${skippedUsers.length} user(s) because they already have the licence.`);
if (skippedUsers.length > 0) console.log("Skipped Users (Action Required):", skippedUsers);
if (failedUsers.length > 0) {
console.log(`\nFailed to process ${failedUsers.length} user(s).`);
console.log("Failed Users:", failedUsers);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment