批量创建OU和AD账号

Posted momingliu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了批量创建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



以上是关于批量创建OU和AD账号的主要内容,如果未能解决你的问题,请参考以下文章

AD域的账户创建和设置

exchange 2013 批量新建邮箱用户

Powershell管理系列(三十三)PowerShell操作之查询AD账号对应的OU存放位置

通过powershell查询OU中被禁用的AD账号,并删除他们的所属组

批量添加AD Group

批量创建AD域用户