Adding users to Active Directory from a CSV file using a PowerShell script. PowerShell script to import into Active Directory forest and create a file with users

Again, it was needed and NOTHING was ready. Everyone writes how to get contacts using the MS Exchange 2007 \ 2010 console. But there are situations - the domain controller is Win2008, and Exchange is 2003. It’s a madhouse, but it happens, what to do... And now it’s required create approximately 6,000 contacts there. It’s not difficult to simply create a contact, but registering the attributes that Exchange requires to work with contacts is another task.
So we need to create a heap mail contacts using powershell v. 2.0.1.1 using the AD module. I will try, as usual, to describe it in the simplest language, understandable to the most inexperienced administrator.

1. Create a file in MS Excel with the name contacts_list, save it in CSV format along the path C:\CSV, and name the columns in the file like this:

Name Mail mailNickname Type proxyAddresses targetAddress

in principle, these parameters are enough to create a full-fledged contact and Exchange sees it and can work with it, no matter in which OU folder in your AD you have it.
What specific fields in the contact object properties do these columns reflect?
Here are the explanations, like a sign)))

Column parameter - Name in the ADSI Attribute Editor (explanation) - Russian-language designation on contact properties

Name - CN (canonical name of the object) - Name
Mail - Mail ( Email) - Email
mailNickname - mailNickname (Exchange alias, alias) - displayed only in the attribute editor
Type - ObjectClass (object class (type)) - displayed only in the attribute editor
proxyAddresses - proxyAddresses (external email address in relation to the domain in SMTP format: [email protected]) - visible only in the attribute editor
targetAddress - targetAddress (external email address in relation to the domain in SMTP format: [email protected]) - visible only in the attribute editor
Fill in the columns, for example

Name Mail mailNickname Type proxyAddresses targetAddress
Vasiliy Terkin [email protected] Partners_Sales_0001 contact SMTP: [email protected] SMTP: [email protected]

Note:
mailNickname should reflect membership in any mailing group, and it is better if it has serial number. I encountered glitches when all contacts had the same mailNickname and the glitches were unpleasant and strange.
proxyAddresses, targetAddress must be in the specified SMTP format: [email protected], otherwise Exchange will not understand the contact and will generate an error about the incorrect format.

2. Create a file with create_contact and extension ps1 and copy the following code there:

Import-CSV -Path "C:\CSV\contacts_list.csv" | ForEach-Object -process (New-ADObject -Path "OU=PostContact,DC=domain,DC=corp,DC=loc al" -Name $_.Name -Type $_.Type -DisplayName $_.Name -OtherAttributes @ ("Mail"=$_.mail; "proxyAddresses"=$_.proxyAddresses; "targetAddress"=$_.targetAddress; "mailNickname"=$_.mailNickname))

What's going on here? Let's take it piece by piece:

Import-CSV -Path "C:\CSV\contacts_list.csv"- the command takes data from a file located at the path C:\CSV\contacts_list.csv

| ForEach-Object -process (- and passes the data into the processing pipeline, with each value processed separately according to the column names

New-ADObject- the pipeline itself is a command for creating an object in AD (help in powershell by calling get-help new-adobject - full)

-Path "OU=PostContact,DC=domain,DC=corp,DC=loc al"- the path where the mail contact will be created. You can view it by opening AD and clicking on the properties of the OU (container) and viewing the path in the “Object” tab and redoing it in accordance with the format in the example. If this parameter is removed, contacts will be created in Users, this is the default path.

-Name $_.Name -Type $_.Type -DisplayName $_.Name - mandatory parameters (Name and Type) and not very mandatory -
DisplayName. They need to be created as witnesses, you can use Cyrillic, you can with Latin letters. There is a length limit, I think, I don’t remember exactly - 64 characters.

-OtherAttributes @("Mail"=$_.mail; "proxyAddresses"=$_.proxyAddresses; "targetAddress"=$_.targetAddress; "mailNickname"=$_.mailNickname))- the most important. Postal addresses cannot be passed simply like Name and Type. Mail addresses are of the otherattributes type - additional attributes, but they can also be passed from the columns of the .CSV file. Don't forget to check all symbols and brackets, there should be 2 brackets at the end.

3. Save files and check paths-C:\CSV - in the file and in real life)))
4. Open powershell on the domain controller (the controller should not be of the ReadOnly type!!!), execute 2 commands in sequence:

Set-ExecutionPolicy Unrestricted

import-module activedirectory

5. Execute C:\CSV\create_contact.ps1
6. We are watching(don't forget to refresh the console) in OU PostContact new email contacts.

And finally, some tips.
- If you have a full-fledged version of powershell, then calling powershell_ise from it will open a very convenient script editor with the ability to launch and other amenities.
- CSV files must be in Unicode encoding, if you have ANSI, there will be an error.
- You can add a lot more columns, and therefore attributes, to an email contact. For example, some Exchange may require a contact attribute such as legacyExchangeDN. It’s not difficult to recognize it - we create a mail contact in AD manually, look at this parameter in the “Attribute Editor” tab (if this tab is not there, turn it on in the console like this: menu View \ Additional Components). Accordingly, add the legacyExchangeDN column to the data file and fill it in edited value copied from the newly created contact, and in the script after "mailNickname"=$_.mailNickname add
"legacyExchangeDN"=$_.legacyExchangeD N. Don't forget the parentheses.

authority February 23, 2014 at 04:47

PowerShell script to import into forest Active Directory and creating a file with users

First I installed and configured WS 2012R2 as DC and after that the question arose of how to add users to it. I had a list of employees in xls file and then I decided, in order not to manually kill users, to optimize this using PowerShell.

There are many examples on the Internet, but they were not very suitable for my solution, some were pieces of code, others did not work at all with WS2012R2, and others added users to specific directories, and I needed to scatter users into more than 70 directories. We also faced the task of how to make a CSV file for PowerShell in accordance with its standards.

First of all, it is necessary to divide the full name into different columns, and it turned out that MS Excel 2013 has a rather interesting tool for this called “Text by Columns”, which is located in the DATA tab.

After this, the login format for users was adopted and it was decided that these would be the first letters of the first name and patronymic and after underscore full surname (for example: aa_petrov). To do this, I had to transliterate them using a VB script.

Translit script - script for Excel

Function Translit(Txt As String) As String Dim Rus As Variant Rus = Array("a", "b", "c", "d", "d", "f", "e", "g", " z", "i", "j", "k", _ "l", "m", "n", "o", "p", "r", "s", "t", "y" ", "f", "x", "ts", "ch", "sh", _ "sch", "b", "s", "b", "e", "yu", "i" , “A”, “B”, “C”, “G”, “D”, “E”, _ “E”, “F”, “Z”, “I”, “J”, “K”, "L", "M", "N", "O", "P", "R", _ "S", "T", "U", "F", "X", "C", " Ch", "Sh", "Sh", "b", "s", "b", "e", "yu", "ya") Dim Eng As Variant Eng = Array("a", "b" , "v", "g", "d", "e", "jo", "zh", "z", "i", "j", _ "k", "l", "m", "n", "o", "p", "r", "s", "t", "u", "f", "h", "c", "ch", _ "sh", " sch", "", "y", "", "e", "yu", "ya", "A", "B", "V", "G", "D", _ "E", "Jo", "Zh", "Z", "I", "J", "K", "L", "M", "N", "O", "P", "R", _" S", "T", "U", "F", "H", "C", "Ch", "Sh", "Sch", "", "Y", "", "E", " Yu", "Ya") For I = 1 To Len(Txt) с = Mid(Txt, I, 1) flag = 0 For J = 0 To 65 If Rus(J) = с Then outchr = Eng(J) flag = 1 Exit For End If Next J If flag Then outstr = outstr & outchr Else outstr = outstr & c Next I Translit = outstr End Function

And also added a function for generating login data:

LOW(LEFT(Translit(LEFT(D2)))&LEFT(Translit(LEFT(E2)))&"_"&Translit(C2))

Passwords were generated using a phrase and a set of random characters:

="Habrhabr"&RANDBETWEEN(1000;9999)

After that I saved the file as .csv with 6 headers Login; Password; LastName; FirstName; MiddleName; OU; JobTitle and changed the file encoding to Unicode, since there are often problems with ANSI.

Then I wrote the following PS script:

Import-Module ActiveDirectory $Users = Import-Csv -Delimiter ";" -Path "C:\Users\Administrator\Desktop\user.csv" $allou = Get-ADOrganizationalUnit -Filter * -SearchBase "OU=Forest,DC=habr,DC=ru" foreach ($User in $Users) ( $ ou = $allou | Where ($_.Name -eq $User.OU) if ($ou) ( $OU = $ou.DistinguishedName ) else ( $OU = "OU=Others,DC=habr,DC=ru"<#Если каталог с таким именем не найден отправляем в OU other#>) $Password = $User.Password $Detailedname = $User.LastName + " " + $User.FirstName + " " + $User.MiddleName $UserFirstname = $User.FirstName $UserLastName = $User.LastName $JobTitle = $User .JobTitle $SAM= $User.Login + "@habr.ru" New-ADUser -Name $Detailedname -SamAccountName $User.Login -UserPrincipalName $SAM -DisplayName $Detailedname -GivenName $User.FirstName -Surname $User.LastName - Title $JobTitle -AccountPassword (ConvertTo-SecureString -AsPlainText "H@brHabr" -Force) -Enabled $true -Path $OU )

This script allows you to scatter users across your own directories, and send those who do not have them to the Other directory.

Thank you for your attention.

Tags: powershell, active directory, excel, csv, windows server 2008, windows server 2008 r2, windows server 2012, windows server 2012r2,

authority February 23, 2014 at 04:47

PowerShell script to import into Active Directory forest and create a file with users

  • PowerShell
  • IT infrastructure

First I installed and configured WS 2012R2 as DC and after that the question arose of how to add users to it. I had a list of employees in an xls file and then I decided, in order not to add users manually, to optimize it using PowerShell.

There are many examples on the Internet, but they were not very suitable for my solution, some were pieces of code, others did not work at all with WS2012R2, and others added users to specific directories, and I needed to scatter users into more than 70 directories. We also faced the task of how to make a CSV file for PowerShell in accordance with its standards.

First of all, it is necessary to divide the full name into different columns, and it turned out that MS Excel 2013 has a rather interesting tool for this called “Text by Columns”, which is located in the DATA tab.

After this, the format of logins for users was adopted and it was decided that these would be the first letters of the first name and patronymic and after the underscore the full last name (for example: aa_petrov). To do this, I had to transliterate them using a VB script.

Translit script - script for Excel

Function Translit(Txt As String) As String Dim Rus As Variant Rus = Array("a", "b", "c", "d", "d", "f", "e", "g", " z", "i", "j", "k", _ "l", "m", "n", "o", "p", "r", "s", "t", "y" ", "f", "x", "ts", "ch", "sh", _ "sch", "b", "s", "b", "e", "yu", "i" , “A”, “B”, “C”, “G”, “D”, “E”, _ “E”, “F”, “Z”, “I”, “J”, “K”, "L", "M", "N", "O", "P", "R", _ "S", "T", "U", "F", "X", "C", " Ch", "Sh", "Sh", "b", "s", "b", "e", "yu", "ya") Dim Eng As Variant Eng = Array("a", "b" , "v", "g", "d", "e", "jo", "zh", "z", "i", "j", _ "k", "l", "m", "n", "o", "p", "r", "s", "t", "u", "f", "h", "c", "ch", _ "sh", " sch", "", "y", "", "e", "yu", "ya", "A", "B", "V", "G", "D", _ "E", "Jo", "Zh", "Z", "I", "J", "K", "L", "M", "N", "O", "P", "R", _" S", "T", "U", "F", "H", "C", "Ch", "Sh", "Sch", "", "Y", "", "E", " Yu", "Ya") For I = 1 To Len(Txt) с = Mid(Txt, I, 1) flag = 0 For J = 0 To 65 If Rus(J) = с Then outchr = Eng(J) flag = 1 Exit For End If Next J If flag Then outstr = outstr & outchr Else outstr = outstr & c Next I Translit = outstr End Function

And also added a function for generating login data:

LOW(LEFT(Translit(LEFT(D2)))&LEFT(Translit(LEFT(E2)))&"_"&Translit(C2))

Passwords were generated using a phrase and a set of random characters:

="Habrhabr"&RANDBETWEEN(1000;9999)

After that I saved the file as .csv with 6 headers Login; Password; LastName; FirstName; MiddleName; OU; JobTitle and changed the file encoding to Unicode, since there are often problems with ANSI.

Then I wrote the following PS script:

Import-Module ActiveDirectory $Users = Import-Csv -Delimiter ";" -Path "C:\Users\Administrator\Desktop\user.csv" $allou = Get-ADOrganizationalUnit -Filter * -SearchBase "OU=Forest,DC=habr,DC=ru" foreach ($User in $Users) ( $ ou = $allou | Where ($_.Name -eq $User.OU) if ($ou) ( $OU = $ou.DistinguishedName ) else ( $OU = "OU=Others,DC=habr,DC=ru"<#Если каталог с таким именем не найден отправляем в OU other#>) $Password = $User.Password $Detailedname = $User.LastName + " " + $User.FirstName + " " + $User.MiddleName $UserFirstname = $User.FirstName $UserLastName = $User.LastName $JobTitle = $User .JobTitle $SAM= $User.Login + "@habr.ru" New-ADUser -Name $Detailedname -SamAccountName $User.Login -UserPrincipalName $SAM -DisplayName $Detailedname -GivenName $User.FirstName -Surname $User.LastName - Title $JobTitle -AccountPassword (ConvertTo-SecureString -AsPlainText "H@brHabr" -Force) -Enabled $true -Path $OU )

This script allows you to scatter users across your own directories, and send those who do not have them to the Other directory.

Thank you for your attention.

Tags: powershell, active directory, excel, csv, windows server 2008, windows server 2008 r2, windows server 2012, windows server 2012r2,

Hi all. Today I will show you how you can automate adding users to AcriveDirecotory using a script. We will take user data from a CSV file.

You can download the archive with the script. In the same archive I put the .net 4.5 installer and powershell 5.1 for 2008R2.

Example of my CSV file:

Full name;position;department;room number;phone number;email;identifier
Ivanov Ivan Ivanovich; director; 76; 345; 123; ;00000001
Petrova Irina Petrovna;laboratory assistant;77;367;124; ;00000002
Vasiliev Vasily Vasilievich; manager; 78; 389; 125; ;00000003
Alexandrov Alexander Alexandrovich;deputy Directors;79;411;126; ;00000004
Sergeev Sergey Sergeevich;laboratory assistant;80;433;127; ;00000005

Accordingly, we will enter all fields into AD. Full name will be divided into last name, first name and patronymic. Our username will be formed from the first letter of the first and last name, translated into transliteration.

In case the username already exists, we take 2 letters from the name and so on.

Pay attention to the ID field. It is just needed in order to determine whether to add a new user or edit an existing one if a namesake appears.

If a record appears with an existing identifier, the user data is updated.

Also, when running our script with the -del key, the users who are present in the CSV file will be deleted from AD.

I tested the script on Windows 2008R2 with powershell 5.1 installed, i.e. it should also work on Windows 2012 and 2016.

In order to install PowerShell 5.1 on 2008R2, at least the first service pack must be installed on it. And also.net 4.5. (I added the .net and powershell installer to the archive with the script. You can download SP1 for Windows 2008R2 from the link).

In order for Powershell to run the script, you need to run the command as an administrator:

Set-ExecutionPolicy bypass

Pay attention to the variables at the beginning of the script; they set the path and name of the csv file, the password that will be assigned to users, as well as the domain name.

Script text:

#Written for the site https://www.mytechnote.ru #For the script to work, you need to update powershell, for this #you first need to install sp1 (https://www.microsoft.com/ru-ru/download/details.aspx?id =5842) #to the server, if not already installed. #Next.net 4.5 (dotNetFX45_Full_setup) #After which you need to update powershell to version 5.1 (in powershell running as administrator, execute Set-ExecutionPolicy bypass, and run the installation script from the powershell51.zip archive) #when running the script, poweshell must be run as 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 file $pathToCSV=".\f_151592b94af8a58e.csv" #password that will be given to new users $defpass= "As12345^" #specify our domain $domain="@test.loc" #transliteration function function global:Translit ( param($inString) $Translit = @( "a" = "a" "A" = "a" " b" = "b" "B" = "b" "c" = "v" "В" = "v" "g" = "g" "G" = "g" "d" = "d" "D " = "d" "e" = "e" "E" = "e" "ё" = "yo" "Ё" = "eo" "zh" = "zh" "Zh" = "zh" "z" = "z" "Z" = "z" "i" = "i" "I" = "i" "th" = "j" "Y" = "j" "k" = "k" "K" = "k" "l" = "l" "L" = "l" "m" = "m" "M" = "m" "n" = "n" "N" = "n" "o" = " o" "O" = "o" "p" = "p" "P" = "p" "p" = "r" "P" = "r" "s" = "s" "C" = "s " "t" = "t" "T" = "t" "y" = "u" "U" = "u" "f" = "f" "F" = "f" "x" = "h" "X" = "h" "ts" = "ts" "C" = "ts" "ch" = "ch" "Ch" = "ch" "sh" = "sh" "Ш" = "sh" ь" = "sch" "Ш" = "sch" "ъ" = "" "ъ" = "" "ы" = "y" "ы" = "y" "ь" = "" "ь" = " " "e" = "e" "E" = "e" "yu" = "yu" "Yu" = "yu" "ya" = "ya" "I" = "ya") $outCHR="" foreach ($CHR in $inCHR = $inString.ToCharArray()) ( if ($Translit[$CHR] -cne $Null) ($outCHR += $Translit[$CHR]) else ($outCHR += $CHR) ) Write-Output $outCHR) #import the csv file into the variable $csv=import-Csv $pathToCSV -Encoding OEM -Delimiter ";" #parse the variable foreach ($user in $csv) ( #put in variable values from csv file $fio="$($user.Full name)" $surname=$fio.split(" ") $name=$fio.split(" ") $sname=$fio.split(" ") $dolzhnost ="$($user.position)" $depart="$($user.department)" $room="$($user."room number")" $phone="$($user."phone number" )" $mail="$($user."email")" $id=$($user."identifier") #translate first and last name into translit $transName=Translit($name) $transSurname=Translit($ surname) #clean up the first letters of the name $shortName="" #add letters to the shortname variable (variable for creating a login) for ($i=1; $i -lt $transName.length; $i++) ( #depending on the number of passes loop, add i letters $shortName=$transName.substring(0,$i) #add first name letters to last name $userName=$shortName+$transSurname try ( #check if there is a user $user=Get-ADUser "$userName" ) catch ( $user=$false ) #if user exists if ($user) ( #get id from AD $IDinAD=Get-ADUser $userName -Properties comment | select comment | ft -HideTableHeaders | out-string #if insurance number from AD matched the number from csv if ($IDinAD -match $id) ( #if we messed up the script without arguments if ($args -eq "" -or !$args) ( #update user 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 } #если запустили скрипт с аргументом -del if ($args -eq "-del") { #удаляем пользователя Remove-ADUser -Identity $userName -Confirm:$false } } #если id не совпадают, и найдено имя пользователя, идем к следующему шагу цикла else { } } #если пользователя не существует else { #и запустили без аргументов if ($args -eq "" -or !$args) { try { $users=get-aduser -Filter "*" -Properties comment | select comment, name } catch { $users=$false } if ($users) { foreach ($user in $users) { #если у какого то пользователя есть id из csv, обновляем его 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 { #добавляем пользователя и прерываем цикл 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 } } } }!}