Import the Active Directory Module
Import-Module ActiveDirectory
Create the New User
New-ADUser -Name "KarimBuzdar" -GivenName "Karim" -Surname "Buzdar" -SamAccountName "kbuzdar" -UserPrincipalName "kbuzdar@faqforge.com" -Path "OU=Users,DC=faqforge,DC=com" -AccountPassword (ConvertTo-SecureString "P@ssw0rd!" -AsPlainText -Force) -Enabled $true
Customize User Attributes
Confirm User Creation
Get-ADUser -Identity kbuzdar
Troubleshooting
These PowerShell commands require the Active Directory module to be installed. It’s best that you install the RSAT tools on your computer. This will prevent the need to load the module every time you run Active Directory related PowerShell commands. You also need to update PowerShell to the latest version to ensure all the cmdlets are updated. Server 2012 has PowerShell 4 installed by default so make sure you update to version 5.1 or the new PowerShell core 7.
Let’s jump right into some examples!
You can install the AD cmdlets on any computerrunning PowerShell. They can be used remotely withany AD domain controller (DC) in a network.
Finding a User Account
(Column widths force us to wrap code. So,although the second command appears ontwo lines here, you would enter it on oneline in the shell. The same holds true for theother multiline commands in this article.)Note that you need to enclose the parameterin quotes if it contains spaces (like in thedisplay name example) or commas (like inthe DN example). This is done to help thePowerShell parser understand that you’repassing in a single string.
Finding and Reporting on Groups ofUser Accounts
If you’d rather have the London data in alist, you can use PowerShell’s Format-Listcmdlet, as in
If you want to convert and save theLondon data in an .html file, you can usePowerShell’s ConvertTo-HTML and Out-File cmdlets in the command
Continue on Page 2
Modifying User Properties
Bulk changes are just as easy. You can relocateeveryone from the London office to theParis office with the command
Modifying User Accounts
Remove-QADObject 'Unlucky One'Continue on Page 3
Creating User Accounts
Easily Manage User Accountsand a Lot More
Не секрет, что начиная с первой версии PowerShell, Microsoft пытается сделать из него основной инструмент администрирования Windows. И во многом это получается! Сегодня на простых примерах, мы покажем возможности PowerShell, которые можно использовать для получения различной информации о пользователях Active Directory и их атрибутах.
Примечание. Ранее для получения информации об атрибутах учетных записей пользователей AD приходилось использовать различные инструменты: консоль ADUC (в том числе сохраненные запросы AD), vbs скрипты, утилиту dsquery и т.п. Выбор инструмента обычно основывался на поставленной задачи и способностях администратора в программировании.
Запускаем окно Powershll с правами администратора и импортируем модуль Active Directory командой:
Import-Module activedirectoryСовет. В Windows Server 2012 и выше этот пункт можно пропустить, так как модуль PowerShell Active Directory подключен по-умолчанию.

help Get-ADUserЧтобы вывести список всех учетных записей домена, выполним команду:
Get-ADUser -filter *Важно. Не рекомендуется выполнять эту команду в доменах с большим количеством аккаунтов, т.к. возможно перегрузка контроллера домена, предоставляющего данные.
Формат возвращаемого списка не очень удобен для использования, выводится только некоторые основные 10 из более 120 атрибутов и свойств учетных записей пользователей (DN, SamAccountName, Name, SID, UPN и т.д) кроме того, мы видим, что информация о времени последней смены пароля отсутствует.
Get-ADUser -identity tuser -properties *- PasswordExpired
- PasswordLastSet
- PasswordNeverExpires
Get-ADUser tuser -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires
Теперь в данных пользователя есть информация о дате смены пароля и времени, когда срок пароля истечет. Представим информацию в более удобном табличном виде:
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires
Чтобы вывести данные пользователей из определенной OU, воспользуемся параметром SearchBase:
Get-ADUser -SearchBase ‘OU=Moscow,DC=winitpro,DC=loc’ -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpiresРезультат выполнения команды можно выгрузить в текстовый файл:
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | ft Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires > C:\temp\users.txtИли в CSV, который в дальнейшем будет удобно экспортировать в Excel (дополнительно с помощью sort-object отсортируем таблицу по столбцу PasswordLastSet , а также добавим условие where – имя пользователя должно содержать строку «Dmitry»):
Get-ADUser -filter * -properties PasswordExpired, PasswordLastSet, PasswordNeverExpires | where {$_.name –like “*Dmitry*”} | sort-object PasswordLastSet | select-object Name, PasswordExpired, PasswordLastSet, PasswordNeverExpires | Export-csv -path c:\temp\user-password-expires-2015.csv
Таким образом, можно построить таблицу с любыми необходимыми атрибутами пользователей Active Directory.
Совет. Для получения данных о компьютерах Active Directory используется командлет Get-ADComputer.
Далее приведем еще несколько полезных вариантов запросов о пользователях Active Directory с помощью различных фильтров. Вы можете их комбинировать для получения необходимого списка пользователей AD:
Вывод пользователей AD, имя которых начинается с Roman:
Get-ADUser -filter {name -like "Roman*"}Чтобы подсчитать общее количество всех аккаунтов в Active Directory:
Get-ADUser -Filter {SamAccountName -like "*"} | Measure-ObjectСписок всех активных (не заблокированных) учетных записей в AD:
Get-ADUser -Filter {Enabled -eq "True"} | Select-Object SamAccountName,Name,Surname,GivenName | Format-TableСписок учетных записей с истекшим сроком действия пароля:
Get-ADUser -filter {Enabled -eq $True} -properties passwordExpired | where {$_.PasswordExpired}Список активных учеток с почтовыми адресами:
Get-ADUser -Filter {(mail -ne "null") -and (Enabled -eq "true")} -Properties Surname,GivenName,mail | Select-Object Name,Surname,GivenName,mail | Format-TableЗадача: для списка учетных записей, которые хранятся в текстовом файле (по одной учетке в строке) нужно получить телефон пользователя в AD и выгрузить информацию в текстовый csv файл (можно легко импортировать в Esxel).
Import-Csv c:\ps\usernsme_list.csv | ForEach {
Get-ADUser -identity $_.user -Properties Name, telephoneNumber |
Select Name, telephoneNumber |
Export-CSV c:\ps\export_ad_list.csv -Append -Encoding UTF8
}Следующий пример позволяет выгрузить адресную книгу предприятия в виде csv файла, который в дальнейшем можно импортировать в Outlook или Mozilla Thunderbird:
Get-ADUser -Filter {(mail -ne "null") -and (Enabled -eq "true")} -Properties Surname,GivenName,mail | Select-Object Name,Surname,GivenName,mail | Export-Csv -NoTypeInformation -Encoding utf8 -delimiter "," $env:temp\mail_list.csvПользователи, которые не меняли свой пароль в течении последних 90 дней:
$90_Days = (Get-Date).adddays(-90)
Get-ADUser -filter {(passwordlastset -le $90_days)}Чтобы получить фотографию пользователя из Active Directory и сохранить ее в jpg файл:
$user = Get-ADUser winadmin -Properties thumbnailPhoto
$user.thumbnailPhoto | Set-Content winadmin.jpg -Encoding byteСписок групп, в которых состоит учетная запись пользователя
Get-AdUser winadmin -Properties memberof | Select memberof -expandproperty memberofExample 1. Unlock AD Account with PowerShell
Step 1. Run the Unlock-ADAccount cmdlet
Unlock-ADAccount -Identity robert.allen
Step 2. Verify Lockout Status
Get-ADUser robert.allen -Properties * | Select-Object LockedOut
The above command will check if the account is locked out.

That is all for example 1.
That was easy, right?
Get Azure Users in Specific Departments
get-mguser -filter "department eq 'Accounting'" -Property displayname, department | select displayname, departmentI hope you enjoyed this article. If you have questions post them below.
Related Content
How to find bad password attempts in Active Directory
Example 4. Unlock AD Account with the AD Pro Toolkit
Step 1: Open the Password Reset & Unlock Tool
From the list of tools click on Password Reset.

Step 2: Click Check for Locked Users

Step 3: Right Click to Unlock
Right-click on any locked account and select unlock.

You will get a pop up letting you know the accounts of been unlocked.

You can also reset passwords and use the troubleshot lockouts option to find the source of account lockouts.

Example 2. Unlock AD Account with Confirmation
This command is the same as the previous example but it adds a confirmation for each account to unlock.
Unlock-AdAccount -identity alice.mills -ConfirmThis will pop up a message to confirm the action.

Tip: If you have repeated accounts locked out you should investigate why before unlocking them all. You can check out this how to guide for troubleshooting account lockouts and tracking down the source of lockout events.
Search-ADAccount -Lockedout | select-object Name, SamAccountName
In this example, I have locked three accounts, I’ll use the Search-ADAccount command to list all the locked accounts.


I’ll run Search-AdAccount -lockout again to confirm all the accounts were unlocked.

You can see above that no accounts are listed.
You can also add the -confirm to this example to confirm each unlock.

Try these commands out and let me know how they work by leaving a comment below.
Get a Count of AD Users in each Department
get-aduser -filter * -properties * | group-object -property departmentFrequently Asked Questions
What is PowerShell and how can I use it to manage Active Directory?
What is an Organizational Unit (OU) in Active Directory?
How do I install the Active Directory module for PowerShell?
Install-WindowsFeature RSAT-AD-PowerShell
The basic command is:
New-ADUser
New-ADUser -Name "John Doe" -SamAccountName jdoe -UserPrincipalName jdoe@example.com -Path "OU=Employees,DC=example,DC=com"
Yes, you can set a password using the -AccountPassword parameter. It requires a Secure String, so your command might look like this:
$UserPassword = ConvertTo-SecureString "P@ssw0rd!" -AsPlainText -Force; New-ADUser -Name "John Doe" -AccountPassword $UserPassword
Is it possible to enable the AD account using PowerShell immediately after creation?
Get-ADUser -Filter 'Name -like "John Doe"'
Search for Users in a Specific Department
Get-ADUser -Filter {department -eq "Accounting"} -property department | Select samaccountname, departmentTo export the results to CSV click the export button.
get-mguser -All -Property displayname, department | select displayname, departmentTopics in this article
Let’s get started.
List Active Directory Users by Department with PowerShell
get-aduser -filter * -properties displayname, department | select displayname, department



