Random Samaccountname generator in AD with PowerShell

charles leon 26 Reputation points
2022-11-17T04:27:38.29+00:00

Hello there, I'm new to PowerShell so I need some help. I need a PS script that will create samaccountname in AD with random and unique characters. Then I want to check the samaccountname against AD (particular OU) to see if the account already exist. If it exists, then I want to try a different account. I want to set a random password for the account. Here's an example for what the account needs to look like:

  1. Account must be 10 characters long
  2. Account MUST start with three unique letters . eg. PED
  3. Account MUST have six random numbers after the unique letters. eg. PED153487
  4. Account MUST have one unique letter at the end. eg. PED153487D

Any help will be highly appreciated. Thanks!

Windows for business Windows Client for IT Pros Directory services Active Directory
0 comments No comments
{count} votes

Accepted answer
  1. Mhd Samer Sawas 151 Reputation points
    2022-11-19T17:07:42.927+00:00

    @charles leon
    The error you got is a normal behavior because Active Directory does not allow you to have more than one user with the same full, name not only within an OU but across the whole domain. You can have two users with the same first and last names but not the same full name. Once you get that error, the script will ask you if you want to create more accounts so you can say yes and then choose a unique full name even if the first and last names are used before.

    Finally, if your query was answered, please mark the last script as an "accepted answer" to close the thread.

    0 comments No comments

13 additional answers

Sort by: Most helpful
  1. charles leon 26 Reputation points
    2022-11-19T00:16:07.177+00:00

    I think it is an AD thing, I don't believe is anything to do with your script. AD just won't allow duplicate names in same OU. Thanks for al your help!!

    1 person found this answer helpful.
    0 comments No comments

  2. Mhd Samer Sawas 151 Reputation points
    2022-11-17T10:39:23.41+00:00

    @charles leon

    $n = 10 # Number of accounts required  
    $Path = 'CN=Users,DC=contoso,DC=com' # OU for the accounts  
    $UPNSuffix = '@contoso.com'  
    $OutputFile = 'Accounts.csv'  
    Clear-Content -Path $OutputFile -Confirm -ErrorAction SilentlyContinue  
      
    for($i=0; $i -lt $n; $i++) {  
      
        $SamaccountnamePart1 = -join ((65..90) | Get-Random -Count 3  | ForEach-Object {[char]$_})  
        $SamaccountnamePart2 = Get-Random -Minimum 100000 -Maximum 999999  
        $SamaccountnamePart3 = -join ((65..90) | Get-Random -Count 1  | ForEach-Object {[char]$_})  
      
        $Samaccountname = -join ($SamaccountnamePart1, $SamaccountnamePart2, $SamaccountnamePart3)  
        $password = -join ((33..126) | Get-Random -Count 12  | ForEach-Object {[char]$_})  
      
        $NewUserParams = @{  
            'SamAccountName' = $Samaccountname  
            'UserPrincipalName' = $Samaccountname + $UPNSuffix  
            'Name' = $Samaccountname  
            'GivenName' = $Samaccountname  
            'Surname' = $Samaccountname  
            'AccountPassword' =  (ConvertTo-SecureString  -String $password -AsPlainText -Force)  
            'Path' = $Path  
            'Enabled' = $True  
        }   
        try {  
            New-ADUser @NewUserParams -ErrorAction Stop # if successful, send created account data to a file  
            [PSCustomObject]@{   
                'SamAccountName' = $Samaccountname  
                'Password' = $Password  
                } | Export-Csv $OutputFile -Append -NoTypeInformation  
        }  
        catch [Microsoft.ActiveDirectory.Management.ADIdentityAlreadyExistsException]{  
            $i-- # Duplicate Samaccountname found, retry this one  
            continue  
        }  
        catch { # some other error occured when creating the account  
            Write-Output $PSITEM.Exception.Message  
        }  
        finally {  
            $Error.Clear()  
        }  
    }  
    

  3. Mhd Samer Sawas 151 Reputation points
    2022-11-18T04:14:23.58+00:00

    @charles leon

    Sure.
    The password already includes numbers, special characters, lowercase and uppercase as you can see from the accounts.csv file generated by the script.
    For the unique prefix 'PED', we'll replace the first part of Samaccountname i.e. $SamaccountnamePart1 in line number 9 with a hardcoded value:
    $SamaccountnamePart1 = 'PED'

    Now the script will look like this:

     $n = 10 # Number of accounts required  
     $Path = 'CN=Users,DC=contoso,DC=com' # OU for the accounts  
     $UPNSuffix = '@contoso.com'  
     $OutputFile = 'Accounts.csv'  
     Clear-Content -Path $OutputFile -Confirm -ErrorAction SilentlyContinue  
          
     for($i=0; $i -lt $n; $i++) {  
          
         $SamaccountnamePart1 = 'PED'  
         $SamaccountnamePart2 = Get-Random -Minimum 100000 -Maximum 999999  
         $SamaccountnamePart3 = -join ((65..90) | Get-Random -Count 1  | ForEach-Object {[char]$_})  
          
         $Samaccountname = -join ($SamaccountnamePart1, $SamaccountnamePart2, $SamaccountnamePart3)  
         $password = -join ((33..126) | Get-Random -Count 12  | ForEach-Object {[char]$_})  
          
         $NewUserParams = @{  
             'SamAccountName' = $Samaccountname  
             'UserPrincipalName' = $Samaccountname + $UPNSuffix  
             'Name' = $Samaccountname  
             'GivenName' = $Samaccountname  
             'Surname' = $Samaccountname  
             'AccountPassword' =  (ConvertTo-SecureString  -String $password -AsPlainText -Force)  
             'Path' = $Path  
             'Enabled' = $True  
         }   
         try {  
             New-ADUser @NewUserParams -ErrorAction Stop # if successful, send created account data to a file  
             [PSCustomObject]@{   
                 'SamAccountName' = $Samaccountname  
                 'Password' = $Password  
                 } | Export-Csv $OutputFile -Append -NoTypeInformation  
         }  
         catch [Microsoft.ActiveDirectory.Management.ADIdentityAlreadyExistsException]{  
             $i-- # Duplicate Samaccountname found, retry this one  
             continue  
         }  
         catch { # some other error occured when creating the account  
             Write-Output $PSITEM.Exception.Message  
         }  
         finally {  
             $Error.Clear()  
         }  
     }  
    

  4. Mhd Samer Sawas 151 Reputation points
    2022-11-18T16:49:24.387+00:00

    @charles leon
    This version will create new accounts as much as needed and takes user input for each name, given name, and surname.

    $Path = 'CN=Users,DC=contoso,DC=com' # OU for the accounts  
    $UPNSuffix = '@contoso.com'  
    $OutputFile = 'Accounts.csv'  
    Clear-Content -Path $OutputFile -Confirm -ErrorAction SilentlyContinue  
    do {  
        $SamaccountnamePart1 = 'PED'  
        $SamaccountnamePart2 = Get-Random -Minimum 100000 -Maximum 999999  
        $SamaccountnamePart3 = -join ((65..90) | Get-Random -Count 1  | ForEach-Object {[char]$_})  
        $Samaccountname = -join ($SamaccountnamePart1, $SamaccountnamePart2, $SamaccountnamePart3)  
        $password = -join ((33..126) | Get-Random -Count 12  | ForEach-Object {[char]$_})  
        $NewUserParams = @{  
            'SamAccountName' = $Samaccountname  
            'UserPrincipalName' = $Samaccountname + $UPNSuffix  
            'Name' = Read-Host -Prompt "Enter Full Name "  
            'GivenName' = Read-Host -Prompt "Enter First Name "  
            'Surname' = Read-Host -Prompt "Enter Last Name "  
            'AccountPassword' =  (ConvertTo-SecureString  -String $password -AsPlainText -Force)  
            'Path' = $Path  
            'Enabled' = $True  
        }   
        try {  
            New-ADUser @NewUserParams -ErrorAction Stop # if successful, send created account data to a file  
            [PSCustomObject]@{   
                'SamAccountName' = $Samaccountname  
                'Password' = $Password  
                'Name' = $NewUserParams.Name  
                'GivenName' = $NewUserParams.GivenName  
                'Surname' = $NewUserParams.Surname  
                } | Export-Csv $OutputFile -Append -NoTypeInformation  
        }  
        catch [Microsoft.ActiveDirectory.Management.ADIdentityAlreadyExistsException]{  
            $i-- # Duplicate Samaccountname found, retry this one  
            continue  
        }  
        catch { # some other error occured when creating the account  
            Write-Output $PSITEM.Exception.Message  
        }  
        finally {  
            $Error.Clear()  
        }  
    } while (  
        ((Read-Host -Prompt "Do you want to create more accounts ? (Type 'y' for yes or any other key to exit)") -eq 'y')  
      )  
    

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.