Remove AD group from Leaver

Leavers! The most ignored process by Support staff the script below will do the following:
Remove AD groups if the user. One of the reason this script helped me when users are added to an AD group which allocates Office 365 License. When the user leaves the organization if the ad group that allocates the license is not removed the license is wasted

Budget plays key role in IT – As we don’t get it much 😛

$users = (Get-ADUser -Filter * -SearchBase "OU Name which the leavers are moved" -Properties *)

$ctime = Get-Date

foreach ($user in $users){

    $daycount = $ctime.Date - $user.modifyTimeStamp.Date
    $Fday = $daycount |select days
        if(($Fday.Days) -gt 7){

               "==================" >> "Output report location.txt"
               $user.Name >> "Output report location.txt"
               $groupname = Get-ADPrincipalGroupMembership $user.SamAccountName | select Name
               Write-Host >> "Output report location.txt"
               $groupname >> "Output report location.txt"
               "==================">> "Output report location.txt"
               Write-Host >> "Output report location.txt"
                Remove-ADGroupMember -Identity $groupname -Members $user.SamAccountName
             
        }else{

           $user.SamAccountName + " : Modified time stamp date is less than 7 days." >> "Output report location.txt" 

        }

       
}    

Published by iamfazul

Author of the site

Leave a comment