What I want to achieve.
I wanna be able to write new account information into my CSV file.
If the SamAccountName is already in use I want the script to add a number to SamAccountName, to differentiate…
The problem.
A number isn’t being added… and I get the error message:
“An attempt was made to add an object to the directory with a name that is already in use” (more on that below).
Im unable to take a print screen or try any solution out right now.
I will continue trying to solve my problem in the morning…
Right now I hope for some ideas…
It does create users, its the second time when I use it the error message comes up.
There is something wrong with the whwile loop I guess… or its idk…
Here is the code:
Import active directory module
Import-Module activedirectory
#Load data from file.csv into $ADUsers variable.
$ADUsers = Import-csv C:\Users\Administrator\Downloads\SimpleScript2\SimpleScript2Users.csv -Delimiter “,”
foreach ($User in $ADUsers)
{
$Username = $User.sAMAccountName
$Password = $User.password
$Firstname = $User.givenName
$Lastname = $User.sn
$OUpath = $user.‘Organizational Unit’
$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 `
-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 $OUpath `
-PasswordNeverExpires $True
#Tell what happened.
Write-Output "$Username was created."
}
The entire 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
From my csv file.