AD.Groups.psm1

function Confirm-ADGroupMembership {
    [CmdletBinding()]
    [OutputType('System.Boolean')]
    param(
        [Parameter(Mandatory = $true)]
        [String]$Identity,
        [Parameter(Mandatory = $true)]
        [String[]]$Groups
    )
    $existingGroups = (Get-ADPrincipalGroupMembership $Identity).SamAccountName

    $extraGroups = $existingGroups | Where-Object {$_ -NotIn $Groups}
    $missingGroups = $Groups | Where-Object {$_ -NotIn $existingGroups}

    if($extraGroups -or $missingGroups){
        return $false
    }else{
        return $true
    }
}

Function Update-ADGroupMembership {
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact='Medium')]
    param(
        [Parameter(Mandatory = $true)]
        [String]$Identity,
        [Parameter(Mandatory = $true)]
        [String[]]$Groups
    )
    $existingGroups = (Get-ADPrincipalGroupMembership $Identity).SamAccountName

    $extraGroups = $existingGroups | Where-Object {$_ -NotIn $Groups}
    $missingGroups = $Groups | Where-Object {$_ -NotIn $existingGroups}

    if ($pscmdlet.ShouldProcess("$Identity group membership", 'update'))
    {
        foreach ($extraGroup in $extraGroups) {
            Write-Warning "Removing $Identity from: $extraGroup"
            Remove-ADGroupMember -Identity $extraGroup -Members $Identity
        }

        foreach ($missingGroup in $missingGroups) {
            Write-Warning "Adding $Identity to: $missingGroup"
            Add-ADGroupMember -Identity $missingGroup -Members $Identity
        }
    }
}