Score:0

PowerShell add users, if exist, add a number

kz flag

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 "[email protected]" `
            -Name "$Firstname $Lastname" `
            -GivenName $Firstname `
            -Surname $Lastname `
            -Enabled $True `
            -DisplayName "$Firstname $Lastname" `
            -EmailAddress "[email protected]" `
            -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,[email protected],[email protected],hosv,Executives,Executives,Head of Finance,Syp9393, 'OU=dd1, OU=My_users, DC=internal, DC=sonic, DC=com'
Marie,Bergqvist,Marie Bergqvist,[email protected],[email protected],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?

yagmoth555 avatar
cn flag
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
br flag
[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`.
kz flag
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! :)
Score:0
pt flag

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

}

Score:0
us flag

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 ...
}
kz flag
Yes! thank you. This seems right.. I will try this in the morning.. I will get back
kz flag
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...
kz flag
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...
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.