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
sweta kumari 55sweta kumari 55 

How deactivate User using apex code ?

Hi,
 In our organization we have 2000 users, I want to deactivate all the users except Administrator profile users.
 
How can I achieve this with peace of Apex code. If possible Could anyone please provide peace of code to achieve this and how to execute that code.

Thanks
Sweta
VinayVinay (Salesforce Developers) 
Hi Sweta,

You can try below sample code.
 
public class deActivateUser{

 public static void deActivationMethod()
 {
   List<user> allUser = [SELECT Email,Id,IsActive, UserRoleId, UserRole.Name FROM User];
   
     for(User u: allUser )
    {
     if(!Pattern.matches('[a-zA-Z0-9._-]+@[a-zA-Z]+.[a-zA-Z]{2,4}[.]{0,1}[a-zA-Z]{0,2}', u.email))
      {
        u.invalid_email__c = true;  
        u.IsActive = false;
        allUser.add(u);
      }
      
     } 
     update allUser;
     }
  }
 
trigger checkUserEmail on User (before insert, before update) {

 deActivateUser.deActivationMethod();

}

Also there is a simple way to export all the users via dataloader and then change the active field to false and upload using dataloader.  

Please mark as Best Answer if above information was helpful.

Thanks,