简体   繁体   中英

Powershell scripting: How to add users to AD Group as user moves from OU,

I am trying to get a script to run that checks if User within an OU and added to the same named Security Group, If the user moves to another OU it needs to be removed from the group and added to the new group

I understand the concept of what I need to do but I cannot get it into PowerShell.

The User will move from OU to OU, and will need to be removed from the current group and added to the New group OU's and Security Groups are named the Same:

OU Structure is 在此处输入图像描述

You need to use the Compare-object cmdlet.

Try this on some Test OUs and Test user accounts to be safe: (Update the variables in the beginning of the script to match your environment...)

$VerbosePreference = "continue"

$UserOULocation = "OU=Test unit,OU=OU1,DC=Domain,DC=local" # please update
$DCServerName = "<servername>" # please update

$ADUsers = Get-ADUser -SearchBase $UserOULocation -filter * -Properties * -Server $DCServerName
$OUNames = Get-ADOrganizationalUnit -SearchBase $UserOULocation -Filter *

Foreach ($ADUser in $ADUsers)
{
    $Groups = $ADUser.MemberOf | % {Get-ADGroup $_}
    $CurrentOU = $ADUser.distinguishedname.Split(",")[1].replace("OU=","")

    If ($Groups)
    {
        # You need to comapre the list of OUs to the groups that the account is a member of
        $Comparing = Compare-Object $CurrentOU $Groups.name

        foreach ($compare in $Comparing | Where-Object {$OUNames.name -contains $_.inputobject})
        {
            If ($Compare.SideIndicator -eq "<=")
            {
                $GroupName = $Compare.InputObject
                Write-Verbose "Adding user $($aduser.name) to group $GroupName"
                Add-ADGroupMember -Identity $Compare.InputObject -Members $ADUser.SamAccountName -Verbose
            }
            else
            {
                $GroupName = $Compare.InputObject
                Write-Verbose "Removing user $($aduser.name) from group $GroupName "
                Remove-ADGroupMember  -Identity $GroupName -Members $ADUser.SamAccountName -Verbose
            }   
        }
    }
    else
    {
        Write-Verbose "No - No groups found for user $($aduser.name)"
        Write-Verbose "ACTION - Adding user to groups"
        Add-ADGroupMember $CurrentOU -Members $ADUser.samaccountname
    }   
}

If this question is about you wanting to move user 'X' to another OU and by doing so:

  1. remove him from the group with the same name as the OU he is in currently
  2. add him to the group with the same name as the OU he is moved to

Then you could do something like this:

# change these to match your configuration
$userToMove    = 'jdoe'
$destinationOU = 'OU=Accounting,DC=Europe,DC=Fabrikam,DC=com'

$user = Get-ADUser -Filter "SamAccountName -eq '$userToMove'" -ErrorAction -SilentlyContinue
if (!$user) { Write-Warning "User '$userToMove' does not exist" }
else {
    # parse the OU from the users DistinguishedName property
    $currentOU    = [regex]::Match($user.DistinguishedName, '(?i)(?=OU=).*$').Value
    # use the OU names to get the names for the groups
    $currentGroup = (Get-ADOrganizationalUnit -Identity $currentOU).Name
    $newGroup     = (Get-ADOrganizationalUnit -Identity $destinationOU).Name
    # if you need the DisplayNames instead,add parameter -Properties DisplayName
    # and get the DisplayName property value. ie:
    #  $currentGroup = (Get-ADOrganizationalUnit -Identity $currentOU -Properties DisplayName).DisplayName
    #  $newGroup     = (Get-ADOrganizationalUnit -Identity $destinationOU -Properties DisplayName).DisplayName

    # remove the user from the group with the same name as the OU he's currently in
    Remove-ADGroupMember -Identity $currentGroup -Members $user
    # add the user to the new group
    Add-ADGroupMember -Identity $newGroup -Members $user
    # finally move the user to the new OU
    $user | Move-ADObject -TargetPath $destinationOU
}

Regex details used in parsing the OU from the users DistinguishedName:

(?=           Assert that the regex below can be matched, starting at this position (positive lookahead)
   OU=        Match the characters “OU=” literally
)            
.             Match any single character that is not a line break character
   *          Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
$             Assert position at the end of the string (or before the line break at the end of the string, if any)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM