批量创建OU和AD账号

 

#导出某个OU下的所有OU
Get-ADOrganizationalUnit -Filter * -SearchBase "OU=智中心,OU=Allusers,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=yy,DC=com","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} 
    }

}

 

 

 

#脚本功能:
#根据从A域导出来的用户账号及其属性,在B域中重新创建,除了密码之外,其他属性(含组织结构)均与A域保持一致
#如果目标OU不存在,则自动创建

####################################################################################################################
<#
#从A域导出域账号属性信息
$ou_search = "ou=usersall,DC=yx,DC=com"
$csv_export = "C:\fordel\allusers.csv"
get-aduser -Filter 'Enabled -eq "True" ' -Properties * -SearchBase $ou_search |select samaccountname,name,DisplayName,Surname,GivenName,mobile,EmployeeID,title,department,DistinguishedName|export-csv  $csv_export  -NoTypeInformation -Encoding Default
#>
######################################################################################################################



#定义保存有A域的账号属性信息
$csv_users = "D:\Scripts\all_users.csv"


#定义错误日志
$log = "D:\Scripts\createuser.log"

#统一设置新密码
#$Password_plain = "password123"

$users = Import-Csv $csv_users -Encoding Default
$Password_sec = ConvertTo-SecureString $Password_plain -AsPlainText -force
$now = Get-Date -UFormat '%Y-%m-%d %H:%M:%S'

# 获取当前域的默认 NC(Naming Context)
$domainDN = (Get-ADDomain).DistinguishedName

#定义函数,新建AD账号及目标OU
function New-ADUserWithOuStructure {
    param($User)
    $samAccountName = $user.samAccountName
    $UserDN = $user.DistinguishedName
    # 解析 DN
    $dnParts = $UserDN -split ','
    if ($dnParts.Count -lt 2) {
        "$now,$samAccountName,Error:无效的DN格式" |Out-File $log -Append
        return
    }

    # 提取 CN(用户名)
    $cnPart = $dnParts[0]
    if ($cnPart -notmatch '^CN=(.+)$') {
        "$now,$samAccountName,DN的第一部分必须是CN=..."|Out-File $log -Append
        return
    }

    #检查OU是否已存在
    $dnPart_old = $dnParts[1..50] -join ','
    $dnPart = $dnPart_old.replace('DC=domain,DC=com',$domainDN)
    if ( -not (Get-ADOrganizationalUnit -Filter { DistinguishedName -eq $dnPart } -ErrorAction SilentlyContinue) )
        {
        # 提取 OU 路径部分(去掉 CN 和 DC 部分)
        $ouParts = @()
        foreach ($part in $dnParts[1..($dnParts.Length - 1)]) {
            if ($part -like "DC=*") { break }
            if ($part -like "OU=*") {
                $ouParts += $part.Substring(3)  # 去掉 "OU="
            } else {
                Write-Warning "$samAccountName,跳过非 OU/DC 组件: $part"
                "$now,$samAccountName,跳过非OU/DC 组件: $part"|Out-File $log -Append
            }
        }

        # 反转 OU 顺序,因为 DN 是从下到上,而我们要从根 OU 向下创建
        [array]::Reverse($ouParts)

        # 构建完整的 OU 路径(从根开始)
        $currentPath = $domainDN
        foreach ($ouName in $ouParts) {
            $ouDN = "OU=$ouName,$currentPath"
            if (-not (Get-ADOrganizationalUnit -Filter { DistinguishedName -eq $ouDN } -ErrorAction SilentlyContinue)) {
                #Write-Host "正在创建 OU: $ouDN"
                New-ADOrganizationalUnit -Name $ouName -Path $currentPath -ProtectedFromAccidentalDeletion $false
            }
            $currentPath = $ouDN
        }
        # 最终 OU 路径即为用户应创建的位置
        $targetOu = $currentPath

        }
    else { $targetOu = $dnPart }

    # 检查用户是否已存在
    $existingUser = Get-ADUser -Filter { Samaccountname -eq $Samaccountname }  -ErrorAction SilentlyContinue
    if ($existingUser) {
        "$now,$Samaccountname 已存在,跳过" |Out-File $log -Append
        return
    }

    $emp_num = $user.EmployeeID  #重置密码
    if ($emp_num -ne '')
        { $Password_plain = "passwordABC" + $emp_num }
    else { $Password_plain = "passwd345" }
    $securePassword = ConvertTo-SecureString $Password_plain -AsPlainText -Force

    # 创建用户
    try {
        $Attributes = @{
            'samAccountName'     = $user.samAccountName
            'UserPrincipalName'  = $user.UserPrincipalName
            'Name'               = $user.Name
            'Enabled'            = $True
            'title'              = $user.Title
            'GivenName'          = $user.GivenName
            'SurName'            = $user.SurName
            'DisplayName'        = $user.DisplayName
            'Department'         = $user.Department
            'EmployeeNumber'     = $user.EmployeeNumber
            'mobile'             = $user.mobile
            'streetaddress'      = $user.streetaddress
            'path'               = $targetOu
        }
        # 创建一个新的哈希表,只保留非空且非空白的值
        $FilteredAttributes = @{}
        foreach ($key in $Attributes.Keys) {
            $value = $Attributes[$key]
            if ($value -ne $null -and $value -notmatch '^\s*$') {
                $FilteredAttributes[$key] = $value
            }
        }
        #$FilteredAttributes
        #AccountPassword放在$Attributes里面不生效
        New-ADUser @FilteredAttributes -AccountPassword $securePassword
        #设置密码永不过期
        Set-ADUser -Identity $FilteredAttributes.SamAccountName -PasswordNeverExpires $true

    } catch {
        $err = $_.exception.message
       "$now,$samAccountName 创建失败,错误:$err" |out-file $log -Append
    }
}



$i = 1
$users_count = $users.Count
Write-Host "共计需要创建 $users_count 个账号" -ForegroundColor Green
foreach ($user in $users[0..4])
    {
    $sam = $user.samaccountname
    Write-Host "正在创建第 $i 个: $sam "  -ForegroundColor Green
    New-ADUserWithOuStructure $user 
    $i += 1
    }

 

posted on 2022-05-10 17:26  momingliu11  阅读(562)  评论(0)    收藏  举报