背景:公司新搭建一套测试AD, 数据要求基本与生产环境一致 ,故而产生这一需求。
通过powershell 脚本实现
一:OU信息导出
点击查看代码
#获取OU 信息
Get-ADOrganizationalUnit -filter * |Select-Object DistinguishedName |Export-Csv -Path 'C:\LocalTemp\OUlist.csv' -Encoding UTF8
二:用户数据导出
点击查看代码
get-aduser -Filter * -Properties * |Select-Object SamAccountName,Name,DisplayName,DistinguishedName,CN,Department,Description,EmailAddress,telephoneNumber,Title |Export-Csv -Path 'C:\LocalTemp\Userlist.csv' -Encoding UTF8
三:批量创建OU
点击查看代码
#创建OU
function create_OU
{
param($ou_Name="" , $ou_Path="")
$ou_DSName=($ou_Name+","+$ou_Path).Split('"')[-1]
$check_Res=Get-ADOrganizationalUnit -Identity $ou_DSName
if($check_Res)
{
Write-Host "存在OU:"$ou_DSName
}
else
{
Write-Host "不存在OU:"$ou_DSName
NEW-ADOrganizationalUnit $ou_Name.split("=")[-1] –path $ou_Path
}
}
foreach ($ou_line in Get-Content 'C:\Users\sa.hans.han\Desktop\OUlist.csv')
{
$ou_path="DC=cdtp,DC=com"
$ou_array=$ou_line.Split(',')
Write-Host "**************开始******************"
foreach ( $ou_item in $ou_array[($ou_array.Length-3)..0])
{
create_OU -ou_Name $ou_item -ou_Path $ou_path
$ou_path=$ou_item+','+$ou_path
#sleep 3000
}
sleep 1
}
四:创建用户
点击查看代码
#判断用户是否存在,若不存在则创建用户
#判断用户所在OU是否正确,若不正确则移动至正确目录
foreach ($user in Import-Csv 'C:\Users\sa.hans.han\Desktop\Userlist.csv')
{
try {
$user_exist= get-aduser -Identity $user.SamAccountName
if ($user_exist.DistinguishedName.split(',',2)[1] -ne $user.DistinguishedName.split(',',2)[1].Replace("DC=innotron,DC=com","OU=AutoBulid_OU,DC=cdtp,DC=com") )
{
Write-Host Warning: Move Accout : $user.SamAccountName From $user_exist.DistinguishedName to $user.DistinguishedName.split(',',2)[1].Replace("DC=innotron,DC=com","OU=AutoBulid_OU,DC=cdtp,DC=com")
Move-ADObject -Identity $user_exist.DistinguishedName -TargetPath $user.DistinguishedName.split(',',2)[1].Replace("DC=innotron,DC=com","OU=AutoBulid_OU,DC=cdtp,DC=com")
}
else
{
Write-Host Info :账号正常 $user.SamAccountName
}
}
catch {
Write-Host Info:用户不存在 $user.SamAccountName
$temp_UserPrincipalName=$user.SamAccountName+"@cdtp.com"
Write-Host $temp_UserPrincipalName
NEW-ADUSER -SamAccountName $user.SamAccountName -UserPrincipalName $temp_UserPrincipalName -Name $user.Name -DisplayName $user.DisplayName -Department $user.Department -Description $user.Description -EmailAddress $user.EmailAddress -MobilePhone $user.telephoneNumber -Title $user.Title -path $user.DistinguishedName.split(',',2)[1].Replace("DC=innotron,DC=com","OU=AutoBulid_OU,DC=cdtp,DC=com")
Write-Host Warning: create AD Account : $user.SamAccountName And Path is $user.DistinguishedName.split(',',2)[1].Replace("DC=innotron,DC=com","OU=AutoBulid_OU,DC=cdtp,DC=com")
#sleep 10
}
}