AutoUpdater - ShadowGroups

If you ever come to a situation where you need to create ShadowGroups, for mailing lists and such

This is a nice start to help you on your way,

 

If you put it to run everyday,


Import-Module ActiveDirectory
<#
 #
 #   ShadowGroups v2.0
 #   by Lennar Kivistik 
 #   www.lennarkivistik.com
 #
 ##>


<# ----------------Settings------------------ #>
    # Select User Organisational Units
    $excludeOU = @('Consultants', 'SharePoint');
    $log_path   = "c:\Script\Logs\ShadowGroups";
    $DomainPath = "OU=Company,DC=Internal,DC=Contoso,DC=com";

<#
 #
 #    This function will log anything to file when used.
 ##>
 
Function Log-Write
{
    Param ([string]$logstring)
    $Logfile = "$log_path\$(get-date -Format ('yyyy-MM')) - shadowgroups-eventlog.log"

    $log = $(get-date -Format ('yyyy-MM-dd HH:mm:ss')) + " - $logstring"

    if (!(Test-Path $Logfile))
    {
        New-Item $Logfile -type file -Force
    }

    Add-content $Logfile -value $log
}   

$ShadowNames = Get-ADOrganizationalUnit -filter * -Searchscope "onelevel" -SearchBase "OU=Users,$DomainPath" |  select name | where {$exclude -notcontains $_.name}

Foreach ($Name in $ShadowNames)
{
    [string]$OU = $Name.name

    $SearchBase  = "OU=$OU,OU=Users,$DomainPath"
    
    $ShadowGroup = "CN=dist-$OU,OU=Shadow Groups,OU=Resources,$DomainPath"

Get-ADGroupMember –Identity $ShadowGroup | 
    Where-Object {$_.distinguishedName –NotMatch $OU} | 
        ForEach-Object {

            Remove-ADPrincipalGroupMembership –Identity $_ –MemberOf $ShadowGroup –Confirm:$false;
            Log-Write "$($_.name) was removed from $ShadowGroup"
        }

Get-ADUser –SearchBase $SearchBase –SearchScope OneLevel –LDAPFilter "(!memberOf=$ShadowGroup)" |
    ForEach-Object {

        Add-ADPrincipalGroupMembership –Identity $_ –MemberOf $ShadowGroup
        Log-Write "$($_.name) was added to $ShadowGroup"
    } # End Get-ADUser

} # End Foreach

Posted on: Monday 12 January 2015