User Account creation Automation on-premise active directory script issue

Good afternoon,

I hope everyone is doing well. I’m trying to create new users from a csv file. I imported the file to the script. The if and else statement on lines 30-34 seem to not work when I use the $SAM variable. If I change the $SAM variable to a string it then accepts the “if” and “else” statement. If I don’t I receive the error below. It doesn’t even attempt to run the “if statement” and it goes directly to the “esle” statement and states the below error. The users I’m creating already exists so I’m trying to fix this part of the code to output existing users to a file. Any help would be greatly appreciated.

`
Here’s the script:

#Import AD module
#Import MSonline to be able to add licenses to the created users
#Prompt user for CSV file path
$filepath = Read-Host -Prompt "Please enter the path of your CSV file"

#Create a new password
$securepassword = ConvertTo-SecureString "Password" -AsPlainText -Force

#Import the file into a variable

$users = Import-Csv $filepath

#Loop through each row and gather information
foreach ($User in $Users) 

{
    #Gather the user's information
    $fname = $user.FirstName
    $lname = $user.Lastname
    $OUpath = $user.ou
    $SAM = $user.SamAccountName 
    $Dept = $user.Department
    $Descr =  $user.Description
    $Email = $user.SamAccountname + "@" + $user.Email
    $ProxyAddr = "SMTP:" + $user.SamAccountName + "@" + $user.ProxyAddresses
    $UPN = $user.SamAccountName + "@" + $user.email
   #Export duplicate sAMAccountName
   #I'm getting an issues with the $SAM variable because it looks like it needs to be called first. 

if (Get-ADUser -f {sAMAccountName -eq $SAM}) {
$SAM | Export-Csv C:\Users\rhall_sa\Desktop\UserCollisions.csv -append
}else
{New-ADUser -Name "$fname $lname" -GivenName $fname -Surname $lname -UserPrincipalName $UPN -Path $OUpath -AccountPassword $securepassword -ChangePasswordAtLogon $true -Description $Descr -Department $Dept -Enabled $true -EmailAddress $Email -OtherAttributes @{'proxyAddresses'=$ProxyAddr}
}

    #Export created users SamAccountname so I can add the licenses to them
    #Add them to the exchange group. 
}

Here’s the error as well `New-ADUser : The specified account already exists
At line:33 char:2

  • {New-ADUser -Name “$fname $lname” -GivenName $fname -Surname $lname - …
  •  + CategoryInfo          : ResourceExists: (CN=Rayne Wilson...=CSIIT,DC=local:String) [New-ADUser], ADIdentityAlreadyExistsException
     + FullyQualifiedErrorId : ActiveDirectoryServer:1316,Microsoft.ActiveDirectory.Management.Commands.NewADUser
    
    

New-ADUser : The specified account already exists
At line:33 char:2

  • {New-ADUser -Name “$fname $lname” -GivenName $fname -Surname $lname - …
  •  + CategoryInfo          : ResourceExists: (CN=Test Testing...=CSIIT,DC=local:String) [New-ADUser], ADIdentityAlreadyExistsException
     + FullyQualifiedErrorId : ActiveDirectoryServer:1316,Microsoft.ActiveDirectory.Management.Commands.NewADUser
    

`

RandallHallJr,
Welcome to the forum. :wave:t4:

Before we proceed: An image of your code is not helpful. Please go back, edit your existing post and share your code as plain text formatted as code.
To do this you use the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.
Thanks in advance

Do the same for error messages and console output. Share it as text formatted as code.

Hey Olaf,

Thanks for the quick response. I’ll add the error as well.

Please format the code as code.

I believe I was able to format it correctly now. Sorry about that.

Almost perfect. :+1:t4: :wink: … give some minutes …

Awesome! I love powershell so far but it’s so difficult lol.

The -Filter parameter on the cmdlet Get-ADUser is quite picky and it actually not a script block - it is a filter string.

Something like this should work I think:

$filepath = Read-Host -Prompt "Please enter the path of your CSV file"
$securepassword = ConvertTo-SecureString "Password" -AsPlainText -Force
$userList = Import-Csv -Path $filepath

foreach ($User in $UserList) {
    $SAM = $user.SamAccountName
    if (Get-ADUser -Filter "sAMAccountName -eq '$SAM'") {
        $User | Export-Csv C:\Users\rhall_sa\Desktop\UserCollisions.csv -Append -NoTypeInformation
    }
    else {
        $NewADUserParams = @{
            Name                  = "$($user.FirstName) $($user.Lastname)"
            GivenName             = $user.FirstName
            Surname               = $user.Lastname
            UserPrincipalName     = '{0}@{1}' -f $user.SamAccountName , $user.email
            Path                  = $user.ou
            AccountPassword       = $securepassword
            ChangePasswordAtLogon = $true
            Description           = $user.Description
            Department            = $Dept
            Enabled               = $true
            EmailAddress          = '{0}@{1}' -f $user.SamAccountname , $user.Email
            OtherAttributes       = @{'proxyAddresses' = $('SMTP:' + $($user.SamAccountName) + '@' + $($user.ProxyAddresses))}
        }
        New-ADUser @NewADUserParams    
    }
}

Please try it with test data first!! :wink:

Hey Olaf,

Thanks for the help but the error still looks like it doesn’t take the “if” statement into account

New-ADUser : The specified account already exists
At line:25 char:9
+         New-ADUser @NewADUserParams
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceExists: (CN=Rayne Wilson...=CSIIT,DC=local:String) [New-ADUser], ADIdentityAlreadyExistsException
    + FullyQualifiedErrorId : ActiveDirectoryServer:1316,Microsoft.ActiveDirectory.Management.Commands.NewADUser
 
New-ADUser : The specified account already exists
At line:25 char:9
+         New-ADUser @NewADUserParams
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceExists: (CN=Test Testing...=CSIIT,DC=local:String) [New-ADUser], ADIdentityAlreadyExistsException
    + FullyQualifiedErrorId : ActiveDirectoryServer:1316,Microsoft.ActiveDirectory.Management.Commands.NewADUser

How about removing all already existing accounts from your input CSV file in advance?

Do data sets get written to the UserCollisions.csv file?

I would like to do that in advance but honestly that’s something else I would have to learn how to do. Nothing writes to usercollision.csv at all. Also, whenever I change the variable to a “string” it produces “Length”
“7”
“8”

It appears to count the number of characters in the csv cell instead of producing the string information to a csv file.

$NonExistingUserList =
foreach ($User in $UserList) {
    try {
        $EsistingUser = Get-ADUser -Identity $User.samaccountname -ErrorAction Stop
    }
    catch {
        $User
    }
}

$NonExistingUserList
2 Likes

Hey Olaf,

Thanks for the code. It worked. I tweaked it a little but I was able to pull the users that need to be created. Afterwards, I ran a script and created the users. I tried to add kiosk licenses to the new users but ran into issues. MSonline commands seem to be funky and it’s not accepting my variables that I use in the cmdlet. They can’t convert the value so they categorize the variable as null. I’m going to add them manually but this is an issue in the future that I would like to solve when I have more time. I love this stuff but it’s stressful lol.