Perrypackettracer / Powershell-scripts-to-use-in-an-active-directory

0 stars 0 forks source link

script to Automate the addition or removal of users from Active Directory groups. #12

Open Perrypackettracer opened 8 months ago

Perrypackettracer commented 8 months ago

Certainly! Below is a PowerShell script that automates the addition or removal of users from Active Directory groups based on predefined criteria. In this example, the script adds users to a security group if they belong to a specific department and removes users who no longer meet the criteria.

# Import Active Directory module
Import-Module ActiveDirectory

# Define the criteria for adding and removing users from the security group
$TargetGroup = "SecurityGroupToUpdate"
$DepartmentCriteria = "IT"

# Get users currently in the target security group
$CurrentGroupMembers = Get-ADGroupMember -Identity $TargetGroup

# Get users who meet the criteria for addition
$UsersToAdd = Get-ADUser -Filter {Department -eq $DepartmentCriteria} -Properties Department

# Get users who no longer meet the criteria for removal
$UsersToRemove = $CurrentGroupMembers | Where-Object { $_.Department -ne $DepartmentCriteria }

# Add users who meet the criteria
foreach ($User in $UsersToAdd) {
    $UserName = $User.SamAccountName

    # Check if the user is not already in the group before adding
    if (-not ($CurrentGroupMembers | Where-Object { $_.SamAccountName -eq $UserName })) {
        Add-ADGroupMember -Identity $TargetGroup -Members $User -Confirm:$false
        Write-Host "User $UserName added to $TargetGroup."
    }
}

# Remove users who no longer meet the criteria
foreach ($User in $UsersToRemove) {
    $UserName = $User.SamAccountName
    Remove-ADGroupMember -Identity $TargetGroup -Members $User -Confirm:$false
    Write-Host "User $UserName removed from $TargetGroup."
}

Explanation:

  1. Modify the $TargetGroup variable with the name of the security group you want to update.

  2. Adjust the $DepartmentCriteria variable to the desired department criteria for adding and removing users.

  3. The script retrieves the current members of the target security group using Get-ADGroupMember.

  4. It then retrieves users who meet the criteria for addition and users who no longer meet the criteria for removal.

  5. The script adds new users to the group and removes users who no longer meet the criteria.

  6. Use this script as a basis and customize it according to your specific criteria for adding or removing users from groups.

  7. Execute the script periodically, for example, using Task Scheduler, to automate the process of updating group memberships based on predefined criteria.