Powershell 自动创建AD账号

很多中小企业使用AD过程中, 可能每天有很多人员入职,相对应的需要IT 来创建AD 账号, 但是企业一般都有创建账号的规则,例如张三, 对应的AD 账号zhangsan, 如果有重名的需要在AD 中先查询一下当前AD 中是否存在zhangsan这个账号, 如果存在则需要在后面加_1再进行查询, 依次类推, 知道没有查询到为止
由于HR 或者用户不希望使用带有2 或者 4 的后缀账号, 则还需要排除, 所以为了实现以上需求, 做到自动判断, 自动例外特殊后缀账号, 再做自动跳过查询, 最终完成AD 账号的创建工作
以下代码, 仅供参考:

$sid = 'zhangsan'
$i = 0
$oupath = 'OU=Domain Users,DC=contoso,DC=com'
$aduser = Get-ADUser -Filter 'samaccountname -eq $sid'
if($aduser -eq $null)
{
    New-ADUser -SamAccountName $sid -Name $sid -UserPrincipalName ($sid + "contoso.com") -DisplayName $sid  -AccountPassword (ConvertTo-SecureString '123456' -AsPlainText -Force) -Path $oupath -Enabled $true
}
else
{
    while ($true)
    {
        $i += 1
        if ($i -eq 2 -or $i -eq 4)
        {
            continue
        }
        else
        {
            $samaccountname = ($sid + '_' + $i.ToString())
            $aduser = Get-ADUser -Filter 'samaccountname -eq $samaccountname'
            if ($aduser -eq $null)
            {
                New-ADUser -SamAccountName $samaccountname -Name $samaccountname -UserPrincipalName ($samaccountname + "contoso.com") -DisplayName $samaccountname  -AccountPassword (ConvertTo-SecureString '123456' -AsPlainText -Force) -Path $oupath -Enabled $true
                Write-Host $samaccountname
                break
            }
        }
    }
}

猜你喜欢

转载自blog.51cto.com/11333879/2547329