Powershell automatically creates an AD account

In the process of many small and medium-sized enterprises using AD, there may be a lot of people joining every day, correspondingly, IT is required to create AD accounts, but companies generally have rules for creating accounts, such as Zhang San, the corresponding AD account zhangsan, if there is a duplicate name You need to check whether the account zhangsan exists in the current AD first in AD. If it exists, you need to add _1 afterwards and then query, and so on, knowing that there is no query so far
because HR or users do not want to use 2 or 4 Suffix accounts need to be excluded, so in order to achieve the above requirements, automatic judgment, automatic exception of special suffix accounts, automatic skip query, and final completion of the AD account creation work The
following code is for reference only:

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

Guess you like

Origin blog.51cto.com/11333879/2547329