You are here

How to Automate ActiveDirectory User Addition Using PowerShell and CSV


Добавление пользователей в Acrive Directory из CSV файла при помощи скрипта PowerShell

Hello to all IT professionals and enthusiasts! Today's tutorial will delve into an efficient way to bulk-add or update users in ActiveDirectory, leveraging the power of scripting. By using a simple CSV file, this automation process becomes seamless.

Download Resources

For those ready to dive in, you can ]]>download the necessary script and tools here]]>. This downloadable package conveniently contains the script alongside installers for .NET 4.5 and PowerShell 5.1 compatible with Windows Server 2008R2.

CSV File Structure

Let's begin by understanding our data source. Here's the structure of the CSV file we'll be using:

Full Name; Position; Department; Room Number; Phone Number; Email Address; Unique Identifier

For instance:

Ivanov Ivan Ivanovich; Director; Dept 76; Room 345; 123-456-7890; [email protected]; ID001

This data format ensures that all necessary user details are captured and can be easily imported into ActiveDirectory.

Important Aspects of the Script

  • Naming Convention: The script processes user names by transliterating the first letters of the first name and surname. In the event of duplicate names, the script smartly incorporates additional characters for differentiation.

  • User Update: The 'Unique Identifier' plays a critical role. If a user with an existing identifier is imported, the script updates their details instead of creating a duplicate entry.

  • Deletion Feature: For those seeking to cleanse their ActiveDirectory, launching the script with the -del parameter removes users listed in the CSV from AD.

Compatibility and Requirements

I've successfully tested the script on Windows Server 2008R2 with PowerShell 5.1. Thus, it should function seamlessly on Windows Server versions 2012 and 2016.

To run the script on Windows Server 2008R2:

  1. Ensure at least the first service pack is installed. If not, ]]>download the SP1 here]]>.
  2. Install .NET 4.5.
  3. Upgrade to PowerShell 5.1.

Once set up, remember to execute the Set-ExecutionPolicy bypass command as an administrator, granting permission to run the script.

Final Thoughts and Script Text

Before running the script, familiarize yourself with the initial variables. These dictate the CSV file's path, default user password, and domain name.

For the tech-savvy readers, here's the script text, tailor-made for this purpose:

#Written for the website https://www.mytechnote.ru
#To run the script, you need to update PowerShell. To do this,
#first, install sp1 (https://www.microsoft.com/ru-ru/download/details.aspx?id=5842)
#on the server if it hasn't been installed yet.
#Next, .net 4.5 (dotNetFX45_Full_setup)
#After that, update PowerShell to version 5.1 (in PowerShell run as an administrator, execute Set-ExecutionPolicy bypass, and then run the installation script from the powershell51.zip archive)
#When launching the script, PowerShell must be run as an administrator.
#When started without a key, users will be added and updated.
#When started with the -del key, users will be deleted.
####################################################################################################################################################################################################

import-module activedirectory
#variables:
#path to the CSV
$pathToCSV=".\f_151592b94af8a58e.csv"
#password for new users
$defpass="As12345^"
#your domain
$domain="@test.loc"


#transliteration function
function global:Translit {
    param([string]$inString)
    $Translit = @{
    [char]'а' = "a"
    [char]'А' = "a"
    [char]'б' = "b"
    [char]'Б' = "b"
    [char]'в' = "v"
    [char]'В' = "v"
    [char]'г' = "g"
    [char]'Г' = "g"
    [char]'д' = "d"
    [char]'Д' = "d"
    [char]'е' = "e"
    [char]'Е' = "e"
    [char]'ё' = "yo"
    [char]'Ё' = "eo"
    [char]'ж' = "zh"
    [char]'Ж' = "zh"
    [char]'з' = "z"
    [char]'З' = "z"
    [char]'и' = "i"
    [char]'И' = "i"
    [char]'й' = "j"
    [char]'Й' = "j"
    [char]'к' = "k"
    [char]'К' = "k"
    [char]'л' = "l"
    [char]'Л' = "l"
    [char]'м' = "m"
    [char]'М' = "m"
    [char]'н' = "n"
    [char]'Н' = "n"
    [char]'о' = "o"
    [char]'О' = "o"
    [char]'п' = "p"
    [char]'П' = "p"
    [char]'р' = "r"
    [char]'Р' = "r"
    [char]'с' = "s"
    [char]'С' = "s"
    [char]'т' = "t"
    [char]'Т' = "t"
    [char]'у' = "u"
    [char]'У' = "u"
    [char]'ф' = "f"
    [char]'Ф' = "f"
    [char]'х' = "h"
    [char]'Х' = "h"
    [char]'ц' = "ts"
    [char]'Ц' = "ts"
    [char]'ч' = "ch"
    [char]'Ч' = "ch"
    [char]'ш' = "sh"
    [char]'Ш' = "sh"
    [char]'щ' = "sch"
    [char]'Щ' = "sch"
    [char]'ъ' = ""
    [char]'Ъ' = ""
    [char]'ы' = "y"
    [char]'Ы' = "y"
    [char]'ь' = ""
    [char]'Ь' = ""
    [char]'э' = "e"
    [char]'Э' = "e"
    [char]'ю' = "yu"
    [char]'Ю' = "yu"
    [char]'я' = "ya"
    [char]'Я' = "ya"
    }
    $outCHR=""
    foreach ($CHR in $inCHR = $inString.ToCharArray())
        {
        if ($Translit[$CHR] -cne $Null )
            {$outCHR += $Translit[$CHR]}
        else
            {$outCHR += $CHR}
        }
    Write-Output $outCHR}

#import csv to the variable
$csv=import-Csv $pathToCSV -Encoding OEM -Delimiter ';'
#compute variable
foreach ($user in $csv)
    {
        #setting csv values
        $fio="$($user.'Full Name')"
        $surname=$fio.split(' ')[0]
        $name=$fio.split(' ')[1]
        $sname=$fio.split(' ')[2]
        $dolzhnost="$($user.Position)"
        $depart="$($user.Department)"
        $room="$($user.'Room Number')"
        $phone="$($user.'Phone Number')"
        $mail="$($user.'Email')"
        $id=$($user.'Unique Identifier')
        #Transliterating name and surname
        $transName=Translit($name)
        $transSurname=Translit($surname)
        #clean first letter in name
        $shortName=""
        #add leters to shortname (for login)
        for ($i=1; $i -lt $transName.length; $i++)
        {
            #add i number of letters
            $shortName=$transName.substring(0,$i)
            #add letters to the name and surname
            $userName=$shortName+$transSurname
            try
            {
                #check if a user exists
                $user=Get-ADUser "$userName"
            }
            catch
            {
                $user=$false
            }
            #if user exists
            if ($user)
            {
                #get his id from AD
                $IDinAD=Get-ADUser $userName -Properties comment | select comment | ft -HideTableHeaders | out-string
                #if id exists
                if ($IDinAD -match $id)
                {
                    #if no arguments 
                    if ($args[0] -eq "" -or !$args[0] )
                    {
                        #renew user's data
                        Set-ADUser -Identity "$userName" -Surname "$surname" -DisplayName "$surname $name $sname" `
                        -OfficePhone "$phone" -EmailAddress "$mail" -Department "$depart" -Title "$dolzhnost" `
                        -UserPrincipalName "$userName$domain" -GivenName "$name" -Office "$room" -enabled $true -SamAccountName "$userName"
                        #break the cycle
                        break
                    }
                    #if script started with -del
                    if ($args[0] -eq "-del")
                    {
                        #remove a user
                         Remove-ADUser -Identity $userName -Confirm:$false
                    }
                }
                #if id not equal, and username found got the the next step
                else
                {
                    
                }
            }
            #if a user doesn't exists
            else
            {
                #and no args
                if ($args[0] -eq "" -or !$args[0])
                {
                    try
                    {
                        $users=get-aduser -Filter "*" -Properties comment | select comment, name
                    }
                    catch
                    {
                        $users=$false
                    }
                    if ($users)
                    {
                        foreach ($user in $users)
                        {
                            #if someone has id from csv - uptate him
                            if ($user.comment -match $id)
                            {
                                $uname=$user.name.toString()
                                $distName=Get-ADObject -Filter 'name -eq $uname'
                                Set-ADUser -Identity "$uname" -Surname "$surname" -DisplayName "$surname $name $sname" `
                                -OfficePhone "$phone" -EmailAddress "$mail" -Department "$depart" -Title "$dolzhnost" `
                                -UserPrincipalName "$userName$domain" -GivenName "$name" -Office "$room" -enabled $true `
                                -SamAccountName "$userName"
                                Rename-ADObject $distName.DistinguishedName -NewName $userName
                            }
                        }
                    }
                        try
                        {
                        #add a user and break the cycle
                        New-ADUser -Name "$userName" -Surname "$surname" -DisplayName "$surname $name $sname" `
                        -OfficePhone "$phone" -EmailAddress "$mail" -Department "$depart" -Title "$dolzhnost" `
                        -UserPrincipalName "$userName$domain" -GivenName "$name" -Office "$room" -OtherAttributes @{comment="$id"} `
                        -AccountPassword (ConvertTo-SecureString -AsPlainText "$defpass" -force) -enabled $true `
                        -ChangePasswordAtLogon $true -SamAccountName "$userName" -erroraction 'silentlycontinue'
                        }
                        catch
                        {
                        }
                        break
                }
            }
        }
    }

If you found this tutorial valuable or have suggestions, leave a comment below. Remember to share with fellow IT professionals who might benefit from this!

0 0

Share the article with your friends in social networks, maybe it will be useful to them.


If the article helped you, you can >>thank the author<<