批量创建OU和AD账号

#导出某个OU下的所有OU
Get-ADOrganizationalUnit -Filter * -SearchBase "OU=智能中心,OU=Staff,DC=yy,DC=com" -SearchScope Subtree |select DistinguishedName
$ous = gc D:\Operations\Scripts\ou-zhineng.txt
$ous.Count

#先对OU进行排序,先创建路径最短的OU
[array]$objs = $null
foreach ($ou in $ous)
{
$count = $ou.Split(",").length
$props=@{'ou'=$ou;'count'=$count}
$obj = New-Object -TypeName psobject -Property $props
$objs += $obj
}
$objs_create = $objs |sort count

#创建OU
foreach ($obj in $objs_create)
{
$ou = $obj.ou.Replace("DC=yy,DC=com","DC=test19,DC=com")
$ou_split = $ou.Split(',')
$ou_name = $ou_split[0].Split("=")[1]
$ou_name
$ou_path = $ou_split[1..100] -join ','
$ou_path
New-ADOrganizationalUnit -Name $ou_name -Path $ou_path

}
#导出AD用户属性
Get-ADUser -Filter * -Properties Name,Surname,GivenName,DisplayName,Department,City,EmployeeNumber,mobile,MobilePhone,StreetAddress,Title,DistinguishedName -SearchBase "OU=智能中心,OU=Staff,DC=yy,DC=com" |select  SamAccountName,Name,Surname,GivenName,DisplayName,Department,City,EmployeeNumber,mobile,MobilePhone,StreetAddress,Title,DistinguishedName |Export-Csv C:\Operations\Scripts\userszhi.csv -Encoding Default -NoTypeInformation

#批量创建AD账号
$users = Import-Csv D:\Operations\Scripts\usersit.csv -Encoding Default

foreach ($user in $users)
{
$AccountPassword = "Y20220510"
$path = ($user.DistinguishedName.Split(",")[1..100] -join ',').replace("DC=yixin,DC=dk","DC=test19,DC=com")
$UserPrincipalName = $user.SamAccountName + "@test19.com"
if ($user.Title.Length -gt 0)  #某些用户属性字段不全,如果Title为空,则减少字段属性
    {
    New-ADUser -Name $user.Name -Path $Path -samAccountName $user.SamAccountName -UserPrincipalName $UserPrincipalName  -Enabled $true -AccountPassword (ConvertTo-SecureString $AccountPassword -AsPlainText -force) -passthru -OtherAttributes @{'title'=$user.Title;'GivenName'=$user.GivenName;'DisplayName'=$user.DisplayName;'Department'=$user.Department;'EmployeeNumber'=$user.EmployeeNumber;'mobile'=$user.mobile;'streetaddress'=$user.streetaddress}
    Get-ADUser $user.SamAccountName |Set-ADUser -Surname $user.Surname
    }
else {
    New-ADUser -Name $user.Name -Path $Path -samAccountName $user.SamAccountName  -UserPrincipalName $UserPrincipalName -Enabled $true -AccountPassword (ConvertTo-SecureString $AccountPassword -AsPlainText -force) -passthru -OtherAttributes @{'DisplayName'=$user.DisplayName}
    }

}

Original: https://www.cnblogs.com/dreamer-fish/p/16254466.html
Author: momingliu11
Title: 批量创建OU和AD账号

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/551639/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球