0

Im creating active directory users from the file usersFile2.csv The users gets added. Right account information is added, for example firstname, lastname, etc...

The PROBLEM. If a user with the same sAMAccountName exists I want the script to add a number to sAMAccountName.. Get-ADuser part is where I need to edit...

# Import active directory module
Import-Module activedirectory

#Load data from file.csv into $ADUsers variable.
$ADUsers = Import-csv C:\Users\Administrator\Downloads\Script5\usersFile2.csv

#Go through each row that has user data in the CSV we just imported.
foreach ($User in $ADUsers)
{
    $Username = $User.sAMAccountName
    $Password = $User.password
    $Firstname = $User.givenName
    $Lastname = $User.sn

    #To see if the user already exists in AD.
    if (Get-ADUser -F {SamAccountName -eq $Username})
    {
         #Tell what happened.
         Write-Output "$Username already existed."
    }
    else
    {
        #If the user does Not exist, then create the account with the attributes.
        New-ADUser `
            -SamAccountName $Username `
            -UserPrincipalName "$Username@sonic.com" `
            -Name "$Firstname $Lastname" `
            -GivenName $Firstname `
            -Surname $Lastname `
            -Enabled $True `
            -DisplayName "$Firstname $Lastname" `
            -EmailAddress "$Username@sonic.com" `
            -Description $user.Description `
            -Department $user.Department `
            -Office $user.Office `
            -AccountPassword (convertto-securestring $Password -AsPlainText -Force) `
            -Path 'OU=dd1, OU=My_users, DC=internal, DC=sonic, DC=com' `
            -PasswordNeverExpires $True
            

        #Tell what happened.
        Write-Output "$Username was new and has been created"
    }
}

Two users from the file usersFile2.csv being added, and it works. but if there is a user with the same sAMAccountName I want the script to add a number...

givenName,sn,displayName,UserPrincipalName,mail,sAMAccountName,Office,Department,Description,password,Path
Holger,Svensson,Holger Svensson,hosv@sonic.com,hosv@sonic.com,hosv,Executives,Executives,Head of Finance,Syp9393, 'OU=dd1, OU=My_users, DC=internal, DC=sonic, DC=com'
Marie,Bergqvist,Marie Bergqvist,mabe@sonic.com,mabe@sonic.com,mabe,Executives,Executives,Head of RND,Syp9393, 'OU=dd1, OU=My_users, DC=internal, DC=sonic, DC=com'

I badly need help.. I have tried for hours.. Im not the one to give up... but man.. Any ideas?

Mathias R. Jessen
  • 25,161
  • 4
  • 63
  • 95
  • Why in your output two users got the same same samaccountname ? I ask as both username are really different, I don't understand the tweak you did there. For me it's a problem there, as someone surelly tried to rename an account, or did something not correct. Its more that exception you should try to fix – yagmoth555 Feb 23 '22 at 13:54
  • [1] use `Get-ADUser` to grab all the users with the same _basic_ user name. `SmithJ` is the base for both `SmithJ` and `SMithJ1`, so you would grab any match for `smithj`. ///// [2] if you get back more than zero, sort by the final digits. ///// [3] grab the highest digit & increment it. ///// [4] use that for your new username - ex = found highest is `SmithJ2`, so use `SmithJ3`. – Lee_Dailey Feb 23 '22 at 15:34
  • yagmoth555 I write in all the user account information in to that file usersFile2.csv.. If I write in the same sAMAccountName the script notifies me, but I want it to automatically add a number, to differentiate... The script doenst create random sAMAccountNames, I have to type them in.. The problem ur talking about, two users with the same samaccountname being created is none existent. but thank you! :) – gunnar20008 Feb 24 '22 at 00:45

2 Answers2

0

Use a while-loop to update and test the username until you find a valid one:

foreach ($User in $ADUsers)
{
    $Username = $User.sAMAccountName
    $Password = $User.password
    $Firstname = $User.givenName
    $Lastname = $User.sn

    $usernameCounter = 0

    while(Get-ADUser -F {SamAccountName -eq $Username} -EA 0)
    {
        # bump numerical suffix value
        $usernameCounter++
        # update candidate username
        $Username = $User.sAMAccountName + $usernameCounter
    }

    New-ADUser ...
}
Mathias R. Jessen
  • 25,161
  • 4
  • 63
  • 95
  • Yes! thank you. This seems right.. I will try this in the morning.. I will get back – gunnar20008 Feb 24 '22 at 00:36
  • Under New-ADUser, i write in the new-ADuser information and i get this error message: `New-ADUser : An attempt was made to add an object to the directory with a name that is already in use At C:\Users\Administrator\Downloads\Script6\script6.ps1:25 char:7 + New-ADUser + ~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (CN=Holger Svens...C=sonic, DC=com:String) [New-ADUser], ADException + FullyQualifiedErrorId : ActiveDirectoryServer:8305,Microsoft.ActiveDirectory.Management.Commands.NewADUser` I guess the $usernameCounter did not get added... – gunnar20008 Feb 24 '22 at 15:29
  • It does create the users with the right account information, but once created new ones doesnt get created.. also thank you for trying to help... – gunnar20008 Feb 24 '22 at 15:37
0

CN must be unique. replace -Name "$Firstname $Lastname" with -Name $Username

Import-Module ActiveDirectory

$ADUsers = Import-Csv 'C:\IT\users.csv'

$UPN = "test.local"

foreach ($User in $ADUsers) {

$password = $User.password
$firstname = $User.firstname
$lastname = $User.lastname
$initials = $User.initials
$OU = $User.ou
$email = $User.email
$jobtitle = $User.jobtitle
$company = $User.company
$department = $User.department
$description = $User.description
if ($lastname.Length -ge 2)
{
    $Username = $FirstName + $LastName.Substring(0,2 )
}
else
{
    $Username = $FirstName + $LastName
}
$usernameCounter = 0

while(Get-ADUser -F {SamAccountName -eq $Username})
{
    $usernameCounter++
    $Username = $username + $usernameCounter
}New-ADUser `
        -SamAccountName $Username `
        -UserPrincipalName "$username@$UPN" `
        -Name $Username `
        -GivenName $firstname `
        -Surname $lastname `
        -Initials $initials `
        -Enabled $True `
        -DisplayName "$firstname $lastname" `
        -Path $OU `
        -Company $company `
        -Description $description `
        -EmailAddress $email `
        -Title $jobtitle `
        -Department $department `
        -AccountPassword (ConvertTo-secureString $password -AsPlainText -Force) -ChangePasswordAtLogon $False

    # If user is created, show message.
    Write-Host "The user account $username is created." -ForegroundColor Cyan

}