function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
ExploreForceExploreForce 

batch job for idnetifying users in multiple groups

How to write batch job?

Batch job should look through all GroupMember table
if one user is in multlipe group, it should remove users from other groups


KaranrajKaranraj
Hi,

1. Query the list of active users in your batch
2. Then inside the excute method check whether the user is assigned to more than one group.

Try the below code
global class userGroupRemoval implements Database.Batchable<sObject> {
	
	String query = 'Select Id from user where isActive = true';
		
	global Database.QueryLocator start(Database.BatchableContext BC) {
		return Database.getQueryLocator(query);
	}

   	global void execute(Database.BatchableContext BC, List<sObject> scope) {

   		List<user> userRecord = (List<user>)scope;
   		List<GroupMember> duplicateGroupId = new List<GroupMember>();
   		Set<Id> userId = new Set<Id>();
   		for(GroupMember gpm : [Select Id,userorGroupId from GroupMember where userorGroupId IN:userRecord]){
   			if(userId.contains(gpm.userorGroupId)){
   				duplicateGroupId.add(gpm);
   			}
   			userId.add(gpm.userorGroupId);
   		}
   		If(duplicateGroupId.size() > 0)
   			delete duplicateGroupId;

	}
	
	global void finish(Database.BatchableContext BC) {
		
	}
	
}

Thanks,
Karan