0
votes

Am trying to upload users in an OU I created and I have .csv file with the fields below; firstname lastname username password ou

Below is the script am running and am getting this error when I run it: "The operation failed because UPN value provided for addition/modification is not unique forest-wide.."

Import-Module activedirectory

$ADUsers = Import-csv; .\ nameofcsv.csv

foreach ($User in $ADUsers) {

$Username   = $User.username
$Password   = $User.password
$Firstname  = $User.firstname
$Lastname   = $User.lastname
$OU         = $User.ou 


if (Get-ADUser -F {SamAccountName -eq $Username})
{
     
     Write-Warning "A user account with username $Username already exist in Active Directory."
}
else
{
    
    
    #Account will be created in the OU provided by the $OU variable read from the CSV file
    New-ADUser `
        -SamAccountName $Username `
        -UserPrincipalName "$Username@domainname" `
        -Name "$Firstname $Lastname" `
        -GivenName $Firstname `
        -Surname $Lastname `
        -Enabled $True `
        -DisplayName "$Lastname, $Firstname" `
        -Path $OU `
        -AccountPassword (convertto-securestring $Password -AsPlainText -Force) 
}

}

1
The script runs but only creates one user from the list and throws the same errorHonest Phiri
Can you provide a sample of the csv you are using?Damien
also what if you tried (-UserPrincipalName ($Username + "@domainname")Damien

1 Answers

0
votes

Code looks okay to me. I've actually used it before too, that if (Get-ADUser -F {SamAccountName -eq $Username}) looked very familiar to me.

In regards to your code, look at

  1. That Import-CSV line. You seem to have a ',' in there. Although you mentioned this only creates one user from the list and throws that error again - so it could be...

The CSV file?

  1. The CSV file you're reading from (nameofcsv.csv). See if you have double quotes '"' around your OU location, i.e "OU=NEW_USERS,DC=Contoso,DC=com".

Also, what happens if your put a -whatif or a -debug on the end of that New-ADuser line? It should get past that first user like you said, then generate some sort of error on the next line.