基于OU的用户移动脚本

任何将读取用户的部门属性(在一个OU和子OU之下)的脚本,并将它们移动到不同的OU(部门已经创build的OU结构名称与属性中的部门相同)。

我们创build了具有不同名称的ou和sub ou作为部门属性

如果您有任何问题,请帮忙


我已经尝试下面的脚本..工作正常…但不是为了子OU …你可以让它工作的子OU以及(现在用户在子OU不search也不移动到子OU甚至子OU创build作为部门名称)….

# 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=Move,DC=testad,DC=com" $LogFile=".\ADS_MoveUsersToOU.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", "department", "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.department $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)" } } } 

你需要做3个改变:

首先,将$searchScopeOneLevel更改为Subtree

接下来,因为您现在正在search子树,所以您还需要在foreach循环中进行检查,只在当前用户位置与$ fullOU不匹配时才尝试移动。 否则,它会尝试将每个对象移动到当前位置,这将会出错,而且效率不高。

最后,您需要更改Move-Adobject -Identity的参数。 您当前的代码假定每个对象始终存在于根OU中。 当你search子树时,它可能不会。 使用Move-Adobject -Identity $_.distinguishedName