locked
Creating users from CSV Powershell - Duplicate Name Handling RRS feed

  • Question

  • Hey all -

    I have a working bulk new-aduser Powershell script. However we are adding in large batches and there are some duplicate names. Example - Testy McTesterson may be in one CSV, and Tested McTesterson may be in another. I'm trying to add the ability to append numbers say 1,2,3 - up to 9 to the sam, upn. in case duplicates are encountered. Working script so far:

    #Create New Users
    $users = Import-Csv -path "C:\Example.csv"
    foreach ($user in $users) {
     
    #Defined hashtable to splat to New-ADUser
    $pass = ConvertTo-SecureString "changeme" -AsPlainText -Force
    $hash = @{
      Office = "$($user.'physicaldeliveryofficename')"
      DisplayName = "$($user.'displayname')"
      Name = "$($user.'givenname') $($user.'sn')"
      EmailAddress = "$($user.'givenname').$($user.'sn')@contoso.com"
      UserPrincipalName = "$($user.'givenname') $($user.'sn')"
      Samaccountname = "$(($user.givenname).substring(0,1))$($user.'sn')"
      GivenName = $($user.'givenname')
      SurName = $($user.'sn')
      Path = "$($user.'destinationOU')"
      AccountPassword = $pass
      Enabled = $True
      ChangePasswordAtLogon = $True
         
      }
     New-ADUser -Verbose @hash -PassThru 
    }




    • Edited by RRD.3 Thursday, June 7, 2018 12:15 AM
    • Moved by Bill_Stewart Monday, July 30, 2018 1:36 PM Abandoned
    Wednesday, June 6, 2018 9:55 PM

All replies

  • You can use a Get-ADUser and assign it to a variable, as in:

    $GotUser = Get-ADUser -Filter whatever

    Then test $GotUser.  If it exists, then you have a duplicate and can invoke the tiebreaker rule.  You may have to do this in a loop because you have to test the tiebreaker user too!


    Ed Crowley MVP "There are seldom good technological solutions to behavioral problems."
    Celebrating 20 years of providing Exchange peer support!

    Wednesday, June 6, 2018 10:06 PM
  • Please look in the Gallery for scripts that do what you ask.  It is more complicated then just checking for the user and you will need to test in a loop to find an available name plus number.

    This is a very common request in forums.


    \_(ツ)_/


    • Edited by jrv Wednesday, June 6, 2018 10:12 PM
    Wednesday, June 6, 2018 10:11 PM