Skip to content

Bulk create AD Users with random passwords

Is it possible to automate the password workflow when creating new AD Users? The answer is: Yes, it’s possible. We can automate the passwords with PowerShell and save them to a new CSV file when creating the Active Directory users. In this article, you will learn how to bulk create AD Users with random passwords.

Before you start to bulk create AD Users

The PowerShell script will automatically create AD users from CSV file and generate random passwords for the users. After the user accounts are created with random passwords, the script will export a new CSV file. In that file, you will have the passwords column with the created passwords.

In the article, we are going to use the following files:

FileInfo
NewUsersRP.csvCSV template that contains the user accounts information
Add-NewUsersRandomPasswords.ps1PowerShell script that will create user accounts with random passwords

Note: If you want to create AD users with your own generated passwords, read the article Create Active Directory Users from CSV with PowerShell.

Create an Organizational Unit (OU)

Good to know is that the script will not create the Organizational Unit (OU). Create the OU if you don’t have it in AD.

Start Active Directory Users and Computers (ADUC) and ensure the OU is valid.

In our example, the OU with the name IT is created and is empty.

Bulk create AD Users with random passwords temp folder before

Download and edit CSV template

Download the CSV template NewUsersRP.csv and save the file in C:\Temp.

Bulk create AD Users with random passwords temp folder

Open the CSV file with your favorite editor. For example, Microsoft Excel. Edit the CSV file to your needs and save it.

Import CSV file in PowerShell

Before you start running the PowerShell script, it’s good to import the CSV file in PowerShell first. Run PowerShell as administrator and use the Import-Csv cmdlet.

If you use the semicolon as a separating character in your CSV file, add the delimiter parameter -Delimiter “;” to your Import-Csv cmdlet. It will be Import-Csv “C:\Temp\NewUsersRP.csv” -Delimiter “;” | Format-Table.

For more information, read Import CSV delimiter PowerShell.

Import-Csv "C:\Temp\NewUsersRP.csv" | Format-Table

The below output appears.

FirstName Initials Lastname Username        Email                      StreetAddress City   ZipCode State Department
--------- -------- -------- --------        -----                      ------------- ----   ------- ----- ----------
Max       MF       Fraser   Max.Fraser      Max.Fraser@exoip.com       21 Baker St   London NW1 6XE       IT
Piers     PB       Bower    Piers.Bower     piers.bower@exoip.com      21 Baker St   London NW1 6XE       IT
Kylie     KD       Davidson Kylie.Davidson  Kylie.Davidson@exoip.com   21 Baker St   London NW1 6XE       IT
Richard   RG       Grant    richard.grant   richard.grant@exoip.com    21 Baker St   London NW1 6XE       IT
Boris     BC       Campbell Boris.Campbell  boris.Campbell@exoip.com   21 Baker St   London NW1 6XE       IT
Nicholas  NM       Murray   Nicholas.Murray Nicholas.Murray@exoip.com  21 Baker St   London NW1 6XE       IT
Leonard   LC       Clark    Leonard.Clark   Leonard.Clark@exoip.com    21 Baker St   London NW1 6XE       IT
Ruth      RD       Dickens  Ruth.Dickens    Ruth.Dickens@exoip.com     21 Baker St   London NW1 6XE       IT
Jonathan  JF       Fisher   Jonathan.Fisher Jonathan.Fisher@exoip.com  21 Baker St   London NW1 6XE       IT
Zoë       ZR       Rees     Zoe.Rees        Zoe.Rees@exoip.com         21 Baker St   London NW1 6XE       IT

If you don’t see all the information in the output, use the Out-GridView cmdlet.

Import-Csv "C:\Temp\NewUsersRP.csv" | Out-GridView

It will show as below screen.

Bulk create AD Users with random passwords Out-GridView

If you get errors when importing the CSV file, troubleshoot further before proceeding to the next step.

Prepare Add-NewUsersRandomPasswords PowerShell script

Download the Powershell script Add-NewUsersRandomPasswords.ps1 and save it in path C:\Scripts on the Management Server or Domain Controller.

Another option is to copy and paste the below code into Notepad. Give it the name Add-NewUsersRandomPasswords.ps1 and place it in the C:\Scripts folder.

<#
    .SYNOPSIS
    Add-NewUsersRandomPasswords.ps1

    .DESCRIPTION
    Create Active Directory users with a random password using PowerShell.

    .LINK
    www.alitajran.com/bulk-create-ad-users-with-random-passwords/

    .NOTES
    Written by: ALI TAJRAN
    Website:    www.alitajran.com
    LinkedIn:   linkedin.com/in/alitajran

    .CHANGELOG
    V1.00, 03/16/2020 - Initial version
    V2.00, 01/28/2024 - Added try/catch and changed to splatting
#>

# Import active directory module for running AD cmdlets
Import-Module ActiveDirectory

$LogDate = Get-Date -f dd-MM-yyyy_HHmmffff

# Location of CSV file that contains the users information
$ImportPath = "C:\Temp\NewUsersRP.csv"

# Location of CSV file that will be exported to including random passwords
$ExportPath = "C:\Temp\Passwords_$LogDate.csv"

# Define UPN
$UPN = "exoip.com"

# Set the password length characters
$PasswordLength = 14

# Store the data from NewUsersRP.csv in the $ADUsers variable
$ADUsers = Import-Csv $ImportPath

# Create an array to store the user data for export
$ExportData = @()

# Randomize passwords
function Get-RandomPassword {
    Param(
        [Parameter(mandatory = $true)]
        [int]$Length
    )
    Begin {
        if ($Length -lt 4) {
            End
        }
        $Numbers = 1..9
        $LettersLower = 'abcdefghijklmnopqrstuvwxyz'.ToCharArray()
        $LettersUpper = 'ABCEDEFHIJKLMNOPQRSTUVWXYZ'.ToCharArray()
        $Special = '!@#$%^&*()=+[{}]/?<>'.ToCharArray()

        # For the 4 character types (upper, lower, numerical, and special)
        $N_Count = [math]::Round($Length * .2)
        $L_Count = [math]::Round($Length * .4)
        $U_Count = [math]::Round($Length * .2)
        $S_Count = [math]::Round($Length * .2)
    }
    Process {
        $Pswrd = $LettersLower | Get-Random -Count $L_Count
        $Pswrd += $Numbers | Get-Random -Count $N_Count
        $Pswrd += $LettersUpper | Get-Random -Count $U_Count
        $Pswrd += $Special | Get-Random -Count $S_Count

        # If the password length isn't long enough (due to rounding), add X special characters
        # Where X is the difference between the desired length and the current length.
        if ($Pswrd.length -lt $Length) {
            $Pswrd += $Special | Get-Random -Count ($Length - $Pswrd.length)
        }

        # Grab the $Pswrd string and randomize the order
        $Pswrd = ($Pswrd | Get-Random -Count $Length) -join ""
    }
    End {
        $Pswrd
    }
}

# Loop through each row containing user details in the CSV file
foreach ($User in $ADUsers) {
    $password = Get-RandomPassword -Length $PasswordLength
    try {
        $userParams = @{
            SamAccountName        = $User.username
            UserPrincipalName     = "$($User.username)@$UPN"
            Name                  = "$($User.firstname) $($User.lastname)"
            GivenName             = $User.firstname
            Surname               = $User.lastname
            Initials              = $User.initials
            Enabled               = $True
            DisplayName           = "$($User.firstname) $($User.lastname)"
            Path                  = $User.ou #This field refers to the OU the user account is to be created in
            City                  = $User.city
            PostalCode            = $User.zipcode
            Company               = $User.company
            State                 = $User.state
            StreetAddress         = $User.streetaddress
            OfficePhone           = $User.telephone
            EmailAddress          = $User.email
            Title                 = $User.jobtitle
            Department            = $User.department
            AccountPassword       = (ConvertTo-SecureString $password -AsPlainText -Force)
            ChangePasswordAtLogon = $True
        }

        # Check to see if the user already exists in AD
        if (Get-ADUser -Filter "SamAccountName -eq '$($User.username)'") {
            # If the user already exists, provide a warning
            Write-Host "A user with the username $($User.username) already exists in Active Directory." -ForegroundColor Yellow
        }
        else {
            # User does not exist then proceed to create the new user account
            # Account will be created in the OU provided by the $OU variable read from the CSV file
            New-ADUser @userParams

            # If the user is created, add the data to the export array
            $ExportData += $User | Add-Member -MemberType NoteProperty -Name "Initial Password" -Value $password -PassThru

            # If the user is created, show a message
            Write-Host "The user $($User.username) is created." -ForegroundColor Green
        }
    }
    catch {
        # If an exception occurs during user creation, handle it here
        Write-Host "Failed to create user $($User.username) - $_" -ForegroundColor Red
    }
}

# Export the data to CSV file
if ($ExportData.Count -gt 0) {
    $ExportData | Export-Csv -Path $ExportPath -NoTypeInformation -Encoding utf8
    Write-Host "CSV file is exported to $ExportPath." -ForegroundColor Cyan
}
else {
    Write-Host "No users were created. CSV file will not be exported." -ForegroundColor Cyan
}
  • Line 27: Change the path if you want to place the CSV file on a different path than C:\Temp.
  • Line 30: Change the path if you want to export the CSV file with passwords to a different path than C:\Temp.
  • Line 33: Change the UserPrincipalName (UPN) to yours. In our example, it’s exoip.com.
  • Line 36: Change the password length characters.

This is how it looks in File Explorer.

Bulk create AD Users with random passwords scripts folder

Run Add-NewUsersRandomPasswords PowerShell script

Run the below command to start the script Add-NewUsersRandomPasswords.ps1 and create AD users.

C:\Scripts\.\Add-NewUsersRandomPasswords.ps1

The script will create the Active Directory users in bulk.

The user Max.Fraser is created.
The user Piers.Bower is created.
The user Kylie.Davidson is created.
The user Richard.Grant is created.
The user Boris.Campbell is created.
The user Nicholas.Murray is created.
The user Leonard.Clark is created.
The user Ruth.Dickens is created.
The user Jonathan.Fisher is created.
The user Zoe.Rees is created.

If you run the script and the user is already created in AD, you will see the below output.

A user with the username Max.Fraser already exists in Active Directory.
A user with the username Piers.Bower already exists in Active Directory.
A user with the username Kylie.Davidson already exists in Active Directory.
A user with the username Richard.Grant already exists in Active Directory.
A user with the username Boris.Campbell already exists in Active Directory.
A user with the username Nicholas.Murray already exists in Active Directory.
A user with the username Leonard.Clark already exists in Active Directory.
A user with the username Ruth.Dickens already exists in Active Directory.
A user with the username Jonathan.Fisher already exists in Active Directory.
A user with the username Zoe.Rees already exists in Active Directory.

The OU with the name IT is filled with new AD users.

Bulk create AD Users with random passwords temp folder after

New CSV file including random passwords

The script creates a new CSV file in the C:\Temp folder. The CSV file will have the name Passwords with the date and time appended.

In this example, Passwords_13-09-2020_20384101.csv.

Open the CSV file with your favorite program. For example, Microsoft Excel.

The CSV file will contain a new column with the name Initial Password. These are the generated passwords.

Bulk create AD Users with random passwords result

Did this help you to bulk create AD Users with random passwords?

Keep reading: Active Directory weak password checker »

Conclusion

You learned how to bulk create AD Users with random passwords. These random passwords are generated automatically with PowerShell and added to the exported CSV file. If you need to bulk create AD users, I recommend you use this PowerShell script.

Did you enjoy this article? You may like the article Bulk move AD users to another OU with PowerShell. Don’t forget to follow us and share this article.

ALI TAJRAN

ALI TAJRAN

ALI TAJRAN is a passionate IT Architect, IT Consultant, and Microsoft Certified Trainer. He started Information Technology at a very young age, and his goal is to teach and inspire others. Read more »

This Post Has 5 Comments

  1. Hi ALI TAJRAN,
    Thank you so much for your script and for sharing your idea.Really helpful.

  2. Hi,

    Is there a way to use the script but not for AD User, only for local user on many computer?
    I mean create a user local account

    Regards

  3. Hi

    This is great content. How would I use this to import already created users, change their password, spit out a report (with passwords) but not create new users?

    thank you

  4. Hello There,
    Thank you fore the script. Really helpful.
    Say if i have different sites and have users in different OU’s how can we modify the script so that when the script is run the users are created in respective OU’s
    Thank you

    1. Hi Pavan,

      I am glad that you find it helpful.

      – Change line 33 in the PS script to the UPN you like to set.
      – Get the OUs distinguishedName that you want to create the users in. Place that in the CSV file under the header OU.

      After the above changes, run the script.

Leave a Reply

Your email address will not be published. Required fields are marked *