I created the following sample script using Google Apps Script that accomplishes what you are looking for. All you need is to change the domain
variable so that it contains the domain of the users that you want to delete.
What the script does is to get the list of users from all the groups, then compares which users have the specified domain in their email address and removes them from the group.
Here is the code:
function removeExternals()
{
let domain = "domain.com";
let groups;
let users;
let externalUsers = [];
groups = AdminDirectory.Groups.list({"customer": "my_customer"});
let groupsIds = [groups.groups.length];
for(let i=0; i< groups.groups.length; i++)
{
groupsIds[i] = groups.groups[i].id;
users = AdminDirectory.Members.list(groupsIds[i]);
for(let x=0; x< groups.groups[i].directMembersCount;x++)
{
try
{
if(users.members[x].email.search(domain)!=-1)
{
//externalUsers.push(users.members[x].email);
AdminDirectory.Members.remove(groupsIds[i], users.members[x].email);
Logger.log(`Deleted: ${users.members[x].email}`);
}
}
catch{};
}
}
}
To test it out you can just create a project in Google Apps Script, paste the code there and change the domain
variable (make sure at least one user with that domain is part of a group). You also need to add the Admin SDK API service to Google Apps Script first by clicking Services
then click Admin SDK API
and then click Add
.
References: