Powershell 自动建立AD帐号

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

ide

$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
            }
        }
    }
}