Knowledge Base

Helpful Info

This script will import users from a CSV into AD.

The script from below is from snippets found on the internet and modified for our use. It comes with no warranty.

 

			
				Import-Module ActiveDirectory

# Store the data from NewUsersFinal.csv in the $ADUsers variable
$ADUsers = Import-Csv "C:\patch\adusers.csv" -Delimiter ","

# Define UPN
$UPN = "domain"

# Loop through each row containing user details in the CSV file
foreach ($User in $ADUsers) {
    try {
        # Define the parameters using a hashtable
        $UserParams = @{
            SamAccountName        = $User.SamAccountName
            UserPrincipalName     = "$($User.SamAccountName)@$UPN"
            Name                  = $User.Name
            GivenName             = $User.GivenName
            Surname               = $User.Surname
            Enabled               = $True
            DisplayName           = "$($User.firstname) $($User.lastname)"
            Path                  = $User.ou #This field refers to the OU the user account is to be created in
            AccountPassword       = (ConvertTo-secureString $User.password -AsPlainText -Force)
            ChangePasswordAtLogon = $True
        }

        echo  $UserParams
            # User does not exist then proceed to create the new user account
            # Account will be created in the OU provided by the $User.ou variable read from the CSV file
            New-ADUser @UserParams

            # If user is created, show message.
            Write-Host "The user $($User.username) is created." -ForegroundColor Green
    }
    catch {
        # Handle any errors that occur during account creation
        Write-Host "Failed to create user $($User.username) - $_" -ForegroundColor Red
    }
}