How to create 2 AD user with same first and last name

Hi all,
Do you know how I can create 2 ad users with the same first and last name?

thank you

What is the problem you’re having?

First name (givenName) and last name (sn) attributes don’t have to be unique within the directory. However, if you’re using them to create the sAMAccountname which must be unique, or the cn which must be unique within the container, then you’ll need to have your creation script handle that, perhaps by appending a number or inserting an initial.

Can you share the code you’re having problems with?

I think that my problem with the CN,but it don’t know how to change the CN every time
this is the script:

Import Exchange Module

$s=New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://ex2019.alex.local/powershell
Import-PSSession -session $s -AllowClobber

Import SFB Module

$SkypeSession = New-PSSession -Credential $Credentials -ConnectionURI https://Skype-Server.alex.local/OcsPowershell
Import-PSSession $SkypeSession -AllowClobber

Grab Variables from User

$ADPath = “OU=Users,OU=Alex,DC=alex,DC=local”

Grab Variables from User

$firstname = Read-Host -Prompt “Enter First Name”

Stop by empty first name

while (!($firstname -eq “”)){

$lastname = Read-Host -Prompt “Enter Last Name”
$password = Read-Host -Prompt “Enter password”

Set username

$i = 1
$username = $firstName + $lastName.Substring(0,$i)
$username = $username.ToLower()

while ((Get-ADUser -filter {SamAccountName -eq $username}).SamAccountName -eq $username)
{

    $username = $firstName + $lastName.Substring(0,$i++)
    $username = $username.ToLower()

}
$email = $username + “@alex.local”

Create the AD User

New-ADUser -Name "$firstname $lastname"
-GivenName $firstname -Surname $lastname
-Displayname “$FirstName $lastname” -UserPrincipalName $email
-SamAccountName $username -AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force)
-Path $ADPath `
-Enabled 1

Create Mailbox

Get-User -OrganizationalUnit alex.local/alex/users -RecipientTypeDetails user | Enable-Mailbox

Create SFB Account

Get-CsAdUser -Ou “alex.local/alex/users” -Filter `
{Enabled -ne $false} | Enable-CsUser -RegistrarPool “Skype-Server.alex.local” -SipAddressType SamAccountName -SipDomain “alex.local”
Get-CsAdUser -OU “alex.local/alex/users” -Filter {Enabled -ne $false} | Measure-Object | FL Count

Write-Host -ForegroundColor Green “The user”$username" created successfully."

$firstname = Read-Host -Prompt “Enter First Name”
Write-verbose “Writing logs”
$failedUsers |ForEach-Object {“$($b).) $($)“; $b++} | out-file -FilePath $LogFolder\FailedUsers.log -Force -Verbose
$successUsers | ForEach-Object {”$($a).) $($
)”; $a++} | out-file -FilePath $LogFolder\successUsers.log -Force -Verbose

$su=(Get-Content “$LogFolder\successUsers.log”).count
$fu=(Get-Content “$LogFolder\FailedUsers.log”).count

Write-Host "$fu Users Creation Failed and " -NoNewline -ForegroundColor red
Write-Host "$su Users Successfully Created " -NoNewline -ForegroundColor green
Write-Host “–> Launching LogsFolder have a Look and review.” -ForegroundColor Magenta
Start-Sleep -Seconds 5
Invoke-Item $LogFolder

}

Write-Host -ForegroundColor Red “Done, Thank You”

Firstly, when posting code in the forum, please can you use the preformatted text </> button. It really helps us with readability, and also makes testing easier as we can copy and paste your code without faffing about replacing curly quote marks to get things working.

What you need to do is test if the user account exists before creating it. If the account exists, you’ll need to modify it based on your company’s policy.

$dn = "CN=$firstname $lastname,$ADPath"
if (-not (Get-ADUser -Identity $dn)) {
    Create the user...    
}
else {
    $name = "$firstname $initial $lastname"
    Create the user...
}

You may consider creating a function to create the user to avoid duplicating code in your conditional code blocks, especially as you should really perform the same checks for the sAMAccountName.

ok thank you but it not working.this is what it did




# Grab Variables from User
$ADPath = "OU=Users,OU=Alex,DC=alex,DC=local"

    

# Grab Variables from User
$firstname = Read-Host -Prompt "Enter First Name"

# Stop by empty first name
while (!($firstname -eq "")){

$lastname = Read-Host  -Prompt  "Enter Last Name"
$password = Read-Host -Prompt "Enter password"
$dn = "CN=$firstname $lastname,$ADPath"
if (-not (Get-ADUser -Identity $dn)) {
New-ADUser `
-Name "$firstname $lastname" `
-GivenName $firstname `
-Surname $lastname `
-Displayname "$FirstName $lastname" `
-UserPrincipalName $email `
-SamAccountName $username  `
-AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force) `
-Path $ADPath `
-Enabled 1 
}
else {
$name = "$firstname $initial $lastname"
New-ADUser `
-Name "$firstname $lastname" `
-GivenName $firstname `
-Surname $lastname `
-Displayname "$FirstName $lastname" `
-UserPrincipalName $email `
-SamAccountName $username  `
-AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force) `
-Path $ADPath `
-Enabled 1
}

# Set username
$i = 1
$username = $firstName + $lastName.Substring(0,$i)
$username = $username.ToLower()
   
while ((Get-ADUser -filter {SamAccountName -eq $username}).SamAccountName -eq $username)
{

        $username = $firstName + $lastName.Substring(0,$i++)
        $username = $username.ToLower()
}
$email = $username + "@alex.local" 



# Create the AD User
New-ADUser `
-Name "$firstname $lastname" `
-GivenName $firstname `
-Surname $lastname `
-Displayname "$FirstName $lastname" `
-UserPrincipalName $email `
-SamAccountName $username  `
-AccountPassword (ConvertTo-SecureString $password -AsPlainText -Force) `
-Path $ADPath `
-Enabled 1 




Write-Host  -ForegroundColor Green "The user"$username" created successfully."

$firstname = Read-Host -Prompt "Enter First Name"

}

Write-Host -ForegroundColor Red "Done, Thank You"

still getting New-ADUser : The specified account already exists

You’re not modifying the sAMAccountName. If you have a user with the same firstname and lastname and you’re generating the sAMAccountName from those values (firstname + initial) that has to be unique as well.

Just to be clear: let’s say you have a user ‘matt bloomfield’ who exists and a user ‘matt brown’ that you want to create:

When you check for the user by searching for the distinguishedName 'CN=matt brown,OU=Users,OU=Alex,DC=alex,DC=local' you won’t find the user so you’re assuming it’s OK to create it. However, the sAMAccountName that you’re generating will be mattb which is the same as the sAMAccountName for the existing user.

You will need to write checks and/or handle errors for any attributes that must be unique.

I understand that
by my sAMAccountName if different
whit this command

while ((Get-ADUser -filter {SamAccountName -eq $username}).SamAccountName -eq $username)
{

        $username = $firstName + $lastName.Substring(0,$i++)
        $username = $username.ToLower()
}

but still it not possbile for me to create 2 users with the same name but with different sAMAccountName

OK, I missed that bit when I scanned through your initital post :eyeglasses:

If you look at your latest post though, you’re executing the code out of order. You need to make sure the sAMAccountName is correct before you try to create the user.

Your current flow is:

  1. Input user details
  2. Check for user with the same name
  3. If the user isn’t found, create the user
  4. If the user is found, modify the name, create the user ** but you’re not setting a value for $Initial so the name will be the same.
  5. Set the sAMAccountName
  6. Create the user.

So, make sure you have a value for $initial so that you can modify the name if required.
Have a look at the order in which you’re doing things.
As previously suggested, use a function to avoid duplicating the create user code.

Wow thank you.
i dont know how to that
can you maybe assist me?

After thinking about it a bit you can get away with not using a function in this script.
I’ve not tested this as I don’t have an AD to test against but it should give you an idea of what you need to do.

$ADPath = "OU=Users,OU=Alex,DC=alex,DC=local"   

$firstname = Read-Host -Prompt "Enter First Name"
$lastname  = Read-Host -Prompt "Enter Last Name"
$initial   = Read-Host -Prompt "Enter Middle Initial"
$password  = Read-Host -Prompt "Enter Password"

$dn = "CN=$firstname $lastname,$ADPath"

if (-not (Get-ADUser -Identity $dn)) {
    $name = "$firstname $lastname"
}
else {
    $name = "$firstname $initial $lastname"
}

$i = 1
$username = "$firstName$($lastName.Substring(0,$i))"
$username = $username.ToLower()

while ((Get-ADUser -filter {SamAccountName -eq $username}).SamAccountName -eq $username) {
    $username = "$firstName$($lastName.Substring(0,$i++))"
    $username = $username.ToLower()
}

$email = "$username@alex.local"

$params = @{
    Name              = $name
    GivenName         = $firstname 
    Surname           = $lastname 
    Displayname       = $name
    UserPrincipalName = $email
    SamAccountName    = $username  
    AccountPassword   = (ConvertTo-SecureString $password -AsPlainText -Force)
    Path              = $ADPath 
    Enabled           = $true 
}

New-ADUser @params

I changed a couple of bits in your code as you should try to:

  • Avoid the + operator for concatenating strings
  • Avoid using backticks
1 Like

thank you
but this is the error that i got after running your script:
Get-ADUser : Directory object not found
At line:11 char:11

  • if (-not (Get-ADUser -Identity $dn)) {
  •       ~~~~~~~~~~~~~~~~~~~~~~~~
    
    • CategoryInfo : ObjectNotFound: (CN=jng hgfghf,O…C=alex,DC=local:ADUser) [Get-ADUser], ADIdentityNotFoundException
    • FullyQualifiedErrorId : ActiveDirectoryCmdlet:Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException,Microsoft.ActiveDirectory.Management.Commands.Ge
      tADUser

New-ADUser : Cannot validate argument on parameter ‘Name’. The argument is null or empty. Provide an argument that is not null or empty, and then try the command
again.
At line:41 char:12

  • New-ADUser @params
  •        ~~~~~~~
    
    • CategoryInfo : InvalidData: (:slight_smile: [New-ADUser], ParameterBindingValidationException
    • FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.NewADUser

OK, sounds like Get-ADUser throws an exception if the user doesn’t exist. Try this instead.
If that doesn’t work, I’ll spin up a VM over the weekend if I get time and test it properly.

$ADPath = "OU=Users,OU=Alex,DC=alex,DC=local"   

$firstname = Read-Host -Prompt "Enter First Name"
$lastname  = Read-Host -Prompt "Enter Last Name"
$initial   = Read-Host -Prompt "Enter Middle Initial"
$password  = Read-Host -Prompt "Enter Password"

$dn = "CN=$firstname $lastname,$ADPath"

try {
    Get-ADUser -Identity $dn
    $name = "$firstname $initial $lastname"
}
catch{
    $name = "$firstname $lastname"
}

$i = 1
$username = "$firstName$($lastName.Substring(0,$i))"
$username = $username.ToLower()

while ((Get-ADUser -filter {SamAccountName -eq $username}).SamAccountName -eq $username) {
    $username = "$firstName$($lastName.Substring(0,$i++))"
    $username = $username.ToLower()
}

$email = "$username@alex.local"

$params = @{
    Name              = $name
    GivenName         = $firstname 
    Surname           = $lastname 
    Displayname       = $name
    UserPrincipalName = $email
    SamAccountName    = $username  
    AccountPassword   = (ConvertTo-SecureString $password -AsPlainText -Force)
    Path              = $ADPath 
    Enabled           = $true 
}

New-ADUser @params

Thank you very much now its working

I have one more issue
I’m using employee numbers instead of Middle Initial
is there a way to force enter just numbers?

You could use a function with advanced parameter and use its validation to limit the input to whatever you need.