# 2012, Tom Schindler # Moves User Accounts from the given Root OU into sub OUs by looking up the company Attribute of the User Object # If the OU does not exist, it will be created (the regular expression filter is removing special characters) Import-Module ActiveDirectory $RootOU = "OU=Guests,DC=mydomain,DC=local" $LogFile=".\ADS_MoveUsersToCompanyOU.txt" $strFilter = "(&(objectCategory=User))" $objDomain = New-Object System.DirectoryServices.DirectoryEntry "LDAP://$RootOU" $objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objSearcher.SearchRoot = $objDomain $objSearcher.PageSize = 1000 $objSearcher.Filter = $strFilter $objSearcher.SearchScope = "OneLevel" $colProplist = "name", "company", "sAMAccountName", "cn" Function Write-Log { [cmdletbinding()] Param( [Parameter(Position=0)] [ValidateNotNullOrEmpty()] [string]$Message ) Write-Host $Message Write-Output "$(Get-Date) $Message" | Out-File -FilePath $LogFile -Append } #end function foreach ($i in $colPropList){ $objSearcher.PropertiesToLoad.Add($i) } $colResults = $objSearcher.FindAll() foreach ($objResult in $colResults) { $objItem = $objResult.Properties; $strCompany = $objItem.company $strCN = $objItem.cn $strName = $objItem.name $strCompany = [System.Text.RegularExpressions.Regex]::Replace($strCompany,"[^1-9a-zA-Z_ ]","") Write-Log "INFO User found : $strName" Write-Log "INFO Company : $strCompany" Write-Log "INFO Canonical Name : $strCN" Write-Log "INFO Distinguished Name : $strdistinguishedName" if (!$strCompany) { Write-Log "WARNING No Company Name found for User: $strName" } else { $fullOU = "OU=$strCompany,$RootOU" $OUExists = [ADSI]::Exists("LDAP://$fullOU") if ($OUExists) { Write-Log "INFO OU exists already:$fullOU" } else { Write-Log "INFO Creating new OU: $fullOU" $objDomain = [ADSI]"LDAP://$RootOU" $objOU = $objDomain.Create("OrganizationalUnit", "OU=$strCompany") try { $objOU.SetInfo() } catch { Write-Log "ERROR Unable to set AD Info (Creating OU: $strCompany)" Write-Log "ERRMSG $($_.Exception.Message)" } } try { Move-ADObject -Identity "CN=$strCN,$RootOU" -TargetPath "OU=$strCompany,$RootOU" } catch { Write-Log "ERROR Unable to move User:CN=$strCN,$RootOU" Write-Log "$($_.Exception.Message)" } } }
6/3/14
Script to Move AD User Objects to another OU depending on an Attribute
Đăng ký:
Đăng Nhận xét (Atom)
Không có nhận xét nào:
Đăng nhận xét