Модуль active directory для windows powershell скачать

Любой системный администратор Windows должен уметь пользоваться не только графическими оснастками AD (чаще всего это ADUC – Active Directory Users and Computer)

Любой системный администратор Windows должен уметь пользоваться не только графическими оснастками AD (чаще всего это ADUC – Active Directory Users and Computer), но и командлетами PowerShell для выполнения повседневных задач администрирования Active Directory. Чаще всего для администрирования домена, управления объектами (пользователями, компьютерами, группами) используется модуль Active Directory для Windows PowerShell. В этой статье мы рассмотрим, как установить модуль RSAT-AD-PowerShell, его базовый функционал и популярные командлеты, которые должны быть полезными при управлении и работе с AD.

Содержание:

  • Как установить модуль Active Directory для PowerShell в Windows 10 и 11?
  • Установка модуля RSAT-AD-PowerShell в Windows Server
  • Основные командлеты модуля Active Directory для PowerShell
  • Импорт модуля Active Directory PowerShell с удаленного компьютера
  • Администрирование AD с помощью модуля Active Directory для PowerShell

Как установить модуль Active Directory для PowerShell в Windows 10 и 11?

Вы можете установить модуль RSAT-AD-PowerShell не только на серверах, но и на рабочих станциях. Этот модуль входит в состав пакета RSAT (Remote Server Administration Tools) для Windows.

В современных билдах Windows 11 и Windows 10 компоненты RSAT устанавливаются онлайн в виде Features on Demand. Вы можете установить модуль с помощью команды:

Add-WindowsCapability -online -Name Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0

установить модуль ad powershell в windows 10 или 11

Или через панель Settings -> Apps -> Optional features -> Add a feature -> RSAT: Active Directory Domain Services and Lightweight Directory Services Tools.

установка модуля powershell rsat adds tools

Для предыдущих версий Windows пакет RSAT нужно было качать и устанавливать вручную. После этого нужно активировать модуль AD для PowerShell из панели управления (Control Panel -> Programs and Features -> Turn Windows features on or off -> Remote Server Administration Tools-> Role Administration Tools -> AD DS and AD LDS Tools).

Для использования командлетов AD в PowerShell Core 6.x, 7.x сначала нужно установить модуль WindowsCompatibility:

Install-Module -Name WindowsCompatibility

Затем загрузите модуль в сессию с помощью команд:

Import-Module -Name WindowsCompatibility
Import-WinModule -Name ActiveDirectory

Import-WinModule загрузка модуля activedirectory в powershell core 7

Теперь вы можете использовать командлеты AD в ваших скриптах на PowerShell Core 7.

Установка модуля RSAT-AD-PowerShell в Windows Server

В Windows Server вы можете установить модуль Active Directory для Windows PowerShell из графической консоли Server Manager или с помощью PowerShell.

Вы можете проверить, что модуль Active Directory установлен с помощью команды:

Get-WindowsFeature -Name «RSAT-AD-PowerShell»

Если модуль отсутствует, установите его:

Install-WindowsFeature -Name "RSAT-AD-PowerShell" –IncludeAllSubFeature

Install-WindowsFeature -Name "RSAT-AD-PowerShell"

Для установки модуля через панель управления Server Manager, перейдите в Add Roles and Features -> Features -> Remote Server Administration tools -> Role Administration Tools -> AD DS and AD LDS Tools -> выберите Active Directory module for Windows PowerShell.

установка Active Directory module for Windows PowerShell в windows server 2016

Не обязательно использовать контроллер домена для администрирования Active Directory с помощью модуля RSAT-AD-PowerShell. Этот модуль можно установить на любом сервере или рабочей станции. На контроллерах домена AD модуль устанавливается автоматически при развертывании роли ADDS (при повышении сервера до DC).

Модуль взаимодействует с AD через службу Active Directory Web Services, которая должна быть запущена на контроллере домена и доступна клиентам по порту TCP 9389. Проверьте, что порт доступен на DC с помощью командлета Test-NetConnection:

tnc MSK-DC01 -port 9389

Основные командлеты модуля Active Directory для PowerShell

В модуле Active Directory для Windows PowerShell имеется большое командлетов для взаимодействия с AD. В текущей версии модуля для Windows Server 2022/Windows 11 доступно 147 PowerShell командлетов для AD.

Проверьте, что модуль установлен на компьютере:

Get-Module -Name ActiveDirectory –ListAvailable

Перед использованием командлетов модуля, его нужно импортировать в сессию PowerShell (начиная с Windows Server 2012 R2/ Windows 8.1 и выше модуль импортируется автоматически):

Import-Module ActiveDirectory

Проверьте, что модуль AD загружен в вашу сессию PowerShell:
Get-Module

проверить что модуль activedirectory загружен в сессию

Вы можете вывести полный список доступных командлетов с помощью команды:

Get-Command –module activedirectory

Общее количество команд в модуле:

Get-Command –module activedirectory |measure-object

Get-Command –module activedirectory

Большинство командлетов модуля RSAT-AD-PowerShell начинаются с префикса Get-, Set-или New-.

  • Командлеты класса Get используются для получения различной информации из AD (Get-ADUser — свойства пользователей, Get-ADComputer – параметры компьютеров, Get-ADGroupMember — состав групп и т.д.). Для их выполнения не нужно быть администратором домена, любой пользователь домена может выполнять скрипты PowerShell для получения значений большинства атрибутов объектов AD (кроме защищенных, как в примере с LAPS).
  • Командлеты класса Set служат для изменения параметров объектов в AD, например, вы можете изменить свойства пользователя (Set-ADUser), компьютера (Set-ADComputer), добавить пользователя в группу и т.д. Для выполнения этих операций у вашей учетной записи должны быть права на объекты, которые вы хотите изменить (см. статью Делегирование прав администратора в AD).
  • Команды, начинающиеся с New- позволяют создать объекты AD: создать пользователя — New-ADUser, группу — New-ADGroup, создать Organizational Unit — New-ADOrganizationalUnit.
  • Командлеты, начинающиеся с Add: добавить пользователю в группу (Add-ADGroupMember), создать гранулированные политики паролей (Add-ADFineGrainedPasswordPolicySubject);
  • Командлеты Remove служат для удаления объектов AD (Remove-ADGroup, Remove-ADComputer, Remove-ADUser).

Есть специфические командлеты PowerShell для управления только определенными компонентами AD:

  • Enable-ADOptionalFeature
    – включить компоненты AD (например, корзину AD для восстановления удаленных объектов)
  • Install-ADServiceAccount
    – настроить учетную запись для службы (MSA, gMSA)
  • Search-ADAccount
    – позволяет найти в AD отключенные, неактивные, заблокированные учетные записи пользователей и компьютеров
  • Enable-ADAccount
    /
    Disable-ADAccount
    /
    Unlock-ADAccount
    – включить/отключить/ разблокировать учетную запись

По умолчанию командлеты PowerShell подключаются к вашему ближайшему контроллеру в вашем домене (LOGONSERVER). С помощью параметра -Server вы можете подключиться к ADDS на другом контроллере домена или в другом домене (список DC в другом домене можно вывести с помощью команды
nltest /dclist:newdomain.com
). Параметр -Server доступен почти для всех командлетов модуля. Например:

Get-ADuser aaivanov -Server msk-dc01.winitpro.ru

Также вы можете указать учетную запись для подключения к AD с помощью параметра -Credential.

$
creds = Get-Credential
Get-ADUser -Filter * -Credential $creds

Получить справку о любом командлете можно так:

get-help New-ADComputer

get-help New-ADComputer

Примеры использования командлетов Active Directory можно вывести так:

(get-help Set-ADUser).examples

В PowerShell ISE при наборе параметров командлетов модуля удобно использовать всплывающие подсказки.

powershell ise подсказки

Импорт модуля Active Directory PowerShell с удаленного компьютера

Не обязательно устанавливать модуль AD PowerShell на все компьютеры. Администраора может удаленно импортировать это модуль с контроллера домена (нужны права администратора домена) или с любого другого компьютера.

Для подключения к удаленном компьютеру исопьзуется PowerShell Remoting. Это требует, чтобы на удаленном компьютере был включен и настроен Windows Remote Management (WinRM).

Создайте новую сесиию с удаленнм компьютером, на котором установлен модуль AD PowerShell:

$rs = New-PSSession -ComputerName DC_or_Comp_with_ADPosh

Импортируйте модуль ActiveDirectory с удаленного компьютера в вашу локальную сессию:

Import-Module -PSsession $rs -Name ActiveDirectory

Теперь вы можете выполнять любые команды из модуля Active Directory на своем компьютере, как будто это модуль установлен локально. При этом они выполняются на удаленном хосте.

Вы можете добавить эти команды в ваш файл профиля PowerShell (например,
notepad $profile.CurrentUserAllHosts
), чтобы автоматически импортировать модуль из удаленной сессии при запуске консоли powershell.exe.

Завершить удалённую сессию можно командой:

Remove-PSSession -Session $rs

Этот же способ с импортом модуля AD через PoweShell implicit remoting позволит вам использовать командлеты PowerShell с хостов Linux and macOS, на которые нельзя установить локальную копию модуля.

Также вы можете использовать модуль Active Directory для PowerShell без установки RSAT. Для этого достаточно скопировать с компьютера с установленным модулем RSAT-AD-PowerShell:

  • Каталог C:WindowsSystem32WindowsPowerShellv1.0Modules
  • Файл ActiveDirectory.Management.dll
  • Файл ActiveDirectory.Management.resources.dll

Затем нужно импортировать модуль в сессию:

Import-Module C:pathMicrosoft.ActiveDirectory.Management.dll
Import-Module C:pathMicrosoft.ActiveDirectory.Management.resources.dll

После этого вы можете использовать все командлеты из модуля AD без установки RSAT.

Администрирование AD с помощью модуля Active Directory для PowerShell

Рассмотрим несколько типовых задач администратора, которые можно выполнить с помощью команд модуля AD для PowerShell.

Полезные примеры использования различных командлетов модуля AD для PowerShell уже описаны на сайте. Следуйте ссылкам по тексту за подробными инструкциями.

New-ADUser: Создать пользователя в AD

Для создания нового пользователя в AD используется использовать командлет New-ADUser. Создать пользователя можно командой:

New-ADUser -Name "Andrey Petrov" -GivenName "Andrey" -Surname "Petrov" -SamAccountName "apetrov" -UserPrincipalName "[email protected] " -Path "OU=Users,OU=Ufa,DC=winitpro,DC=loc" -AccountPassword(Read-Host -AsSecureString "Input Password") -Enabled $true

Более подробно о команде New-ADUser (в том числе пример массового создания учетных записей в домене) читайте в статье .

Get-ADComputer: Получить информацию о компьютерах домена

Чтобы вывести информацию о компьютерах в определённом OU (имя компьютера и дата последней регистрации в сети) используйте командлет Get-ADComputer:

Get-ADComputer -SearchBase ‘OU=Russia,DC=winitpro,DC=ru’ -Filter * -Properties * | FT Name, LastLogonDate -Autosize

Add-AdGroupMember: Добавить пользователя в группу AD

Чтобы добавить пользователей в существующую группу безопасности в домене AD, выполните команду:

Add-AdGroupMember -Identity MskSales -Members apterov, divanov

Вывести список пользователей в группе AD и выгрузить его в файл:

Get-ADGroupMember MskSales -recursive| ft samaccountname| Out-File c:scriptexport_users.csv

Более подробно об управлении группами AD из PowerShell.

Set-ADAccountPassword: Сброс пароля пользователя в AD

Чтобы сбросить пароль пользователя в AD из PowerShell, выполните:

Set-ADAccountPassword apterov -Reset -NewPassword (ConvertTo-SecureString -AsPlainText “[email protected]” -Force -Verbose) –PassThru

Блокировка/разблокировка пользователя

Отключить учетную запись:

Disable-ADAccount apterov

Включить учетную запись:

Enable-ADAccount apterov

Разблокировать аккаунт после блокировки парольной политикой:

Unlock-ADAccount apterov

Search-ADAccount: Поиск неактивных компьютеров в домене

Чтобы найти и заблокировать в домене все компьютеры, которые не регистрировались в сети более 100 дней, воспользуйтесь командлетом Search-ADAccount:

$timespan = New-Timespan –Days 100
Search-ADAccount -AccountInactive -ComputersOnly –TimeSpan $timespan | Disable-ADAccount

New-ADOrganizationalUnit: Создать структуру OU в AD

Чтобы быстро создать типовую структуры Organizational Unit в AD, можно воспользоваться скриптом PowerShell. Допустим, нам нужно создать несколько OU с городами, в которых создать типовые контейнеры. Вручную через графическую консоль ADUC такую структуру создавать довольно долго, а модуль AD для PowerShell позволяет решить такую задачу за несколько секунд (не считая время на написание скрипта):

$fqdn = Get-ADDomain
$fulldomain = $fqdn.DNSRoot
$domain = $fulldomain.split(".")
$Dom = $domain[0]
$Ext = $domain[1]
$Sites = ("SPB","MSK","Sochi")
$Services = ("Users","Admins","Computers","Servers","Contacts")
$FirstOU ="Russia"
New-ADOrganizationalUnit -Name $FirstOU -Description $FirstOU -Path "DC=$Dom,DC=$EXT" -ProtectedFromAccidentalDeletion $false
foreach ($S in $Sites)
{
New-ADOrganizationalUnit -Name $S -Description "$S" -Path "OU=$FirstOU,DC=$Dom,DC=$EXT" -ProtectedFromAccidentalDeletion $false
foreach ($Serv in $Services)
{
New-ADOrganizationalUnit -Name $Serv -Description "$S $Serv" -Path "OU=$S,OU=$FirstOU,DC=$Dom,DC=$EXT" -ProtectedFromAccidentalDeletion $false
}
}


После выполнения скрипта у нас в AD появилась такая структура OU.

New-ADOrganizationalUnit

Для переноса объектов между контейнерами AD можно использовать командлет Move-ADObject:

$TargetOU = "OU=Buhgalteriya,OU=Computers,DC=corp,DC=winitpro,DC=ru"
Get-ADComputer -Filter 'Name -like "BuhPC*"' | Move-ADObject -TargetPath $TargetOU

Get-ADReplicationFailure: Проверка репликации в AD

С помощью командлета Get-ADReplicationFailure можно проверить состояние репликации между контроллерами домена AD:

Get-ADReplicationFailure -Target DC01,DC02

Получить информацию обо всех DC в домене с помощью командлета Get-AdDomainController:

Get-ADDomainController –filter * | select hostname,IPv4Address,IsGlobalCatalog,IsReadOnly,OperatingSystem | format-table –auto

Get-ADDomainController

В этой статье мы рассмотрели, как установить и использовать модулья AD PowerShell для администрирования домена. Надеюсь, эта статья подтолкнет вас к дальнейшему исследованию возможностей этого модуля и автоматизации большинства задач управления AD.

Сегодня я покажу, как установить и использовать модуль администрирования Active Directory для Windows PowerShell. Командлеты этого модуля можно использовать для получения информации и управлением различными объектами и параметрами AD. Данный модуль в серверных ОС устанавливается в виде отдельного компонента. На десктопные ОС (Windows 10, 8.1, 7) придется установить пакет Remote Server Administration Tools (RSAT) в состав которого входит модуль для взаимодействия с AD из PowerShell. Кроме этого модуля в состав RSAT входят все необходимые графические оснастки управления, утилиты командной строки и модули Windows PowerShell для администрирования Windows и AD. Данный пакет для вашей версии ОС нужно самостоятельно скачать с сайта Microsoft.

    Содержание:

  • Установка модуля Active Directory для Windows PowerShell
  • Импорт и использование модуля PowerShell для Active Directory

Установка модуля Active Directory для Windows PowerShell

Модуль Active Directory для Windows PowerShell впервые появился в Windows Server 2008 R2. Он автоматически устанавливается на контроллерах домена при их установке на них роли ADDS. Для использования комадлетов PowerShell из модуля AD в домене должен быть хотя бы один контроллер с Windows Server 2008 R2 или выше. Если в вашей сети имеются DC только с Windows Server 2003 и 2008, необходимо скачать и установить Active Directory Management Gateway Service. Командлеты PowerShell из модуля Active Directory взаимодействуют с веб-сервисом, который является частью контролера домена с ролью ADDS.

Вы можете установить модуль Active Directory для Windows PowerShell не только на контроллер домена, но и на любой рядовой сервер домена или рабочую станцию. В Windows Server 2016 установить модуль Active Directory для Windows PowerShell можно из графической консоли Server Manager с помощью мастера добавления ролей и компонентов. Достаточно запустить мастер и на этапе выбора компонентов нужно выбрать пункт Средства удаленного администрирования сервера -> Средства администрирования ролей -> Средства AD DS и AD LDS -> Модуль Active Directory для Windows PowerShell (Remote Server Administration Tools > Role Administration Tools > AD DS and AD LDS Tools ->Active Directory module for Windows PowerShell).

установка Модуля Active Directory для Windows PowerShell

Данный модуль можно установит и с помощью PowerShell. Откройте консоль PowerShell с правами администратора и выполните команды:

Import-Module ServerManager

Add-WindowsFeature -Name "RSAT-AD-PowerShell" –IncludeAllSubFeature

установка модуля RSAT-AD-PowerShell из консоли powershell

В Windows 10, Windows 8.1 и Windows 10 для установки модуля RSAT-AD-PowerShell нужно сначала установить соответствующую версию RSAT, после этого модуль нужно включить в Панели управления (Панель управления -> Программы ->Программы и компоненты и нажмите «Включить компоненты Windows» -> Remote Server Administration Tools -> Role Administration Tools -> AD DS and AD LDS Tools -> включите компонент Active Directory Module for Windows POwerShell.

Включить компоненты Windows - Active Directory Module for Windows POwerShell

Либо можно установить модуль с помощью PowerShell:

Enable-WindowsOptionalFeature -Online -FeatureName RSATClient-Roles-AD-Powershell

Импорт и использование модуля PowerShell для Active Directory

В Windows 7 и Windows Server 2008 R2, на которых установлен PowerShell 2.0, чтобы начать пользоваться модулем AD необходимо импортировать его в сессию PowerShell командой:

Import-Module activedirectory

Import-Module activedirectory

Кроме того, вы можете экспортировать модуль с удаленной машины, где он уже установлен и импортировать его в свою сессию PowerShell:

$MySession = New-PSSession -ComputerName MyDomainController
Export-PSsession -Session $MySession -Module ActiveDirectory -OutputModule RemoteADPosh
Remove-PSSession -Session $MySession
Import-Module RemoteADPosh

В Windows Server 2012 R2/ 2016 и Windows 8.1 / Windows 10 модуль (если он установлен) импортируется в сессию автоматически.

Если компьютер включен в домен, по умолчанию создается диск по имени AD:..Вы можете перейти на этот диск командой CD и использовать привычные команды работы с файловой системой для навигации по этому диску. Пути представлены в формате X500.

PS C:> cd AD:
PS AD:> dir

PS AD:> cd "DC=vmblog,DC=ru"

навигация по AD из powershell

Вывести список доступных командлетов модуля для работы с Active Directory можно так:

Get-Command -Module ActiveDirectory

все команды модуля ActiveDirectory

В различных версия Windows доступно разное количество командлетов:

  • Windows Server 2008 R2 — 76 командлетов.
  • Windows Server 2012 — 135 командлетов
  • Windows Server 2012 R2 / 2016 — 147 командлетов.

Итак, теперь вы можете использовать командлеты PowerShell для администрирования AD. На нашем сайты вы можете познакомиться с использованием следующих командлетов из модуля AD для PowerShell: Get-ADGroupMember , Add-ADGroupMember , Move-ADDirectoryServerOperationMasterRole, New-ADGroup.

This guide has been updated for the latest Windows versions Windows 11 and Windows Server 2022. You’ll learn how to install the Active Directory (AD) module for PowerShell Core 6.0, PowerShell 7 and Windows PowerShell. For Windows PowerShell, the tutorial describes how to install the AD module for Windows 7, Windows 8, Windows 8.1, Windows 10, Windows 11 Windows Server 2008 R2, Windows Server 2012 R2, and Windows Server 2016, Windows Server 2010 and Windows Server 2022. You’ll also learn how to work with the AD module on other systems such as macOS or Linux with the help of PowerShell remoting.

Contents

  1. Windows 7
  2. Windows Server 2008 R2
  3. Windows 8, Windows 8.1
  4. Windows 10
  5. Windows 11
  6. On Windows 11 with PowerShell
  7. Windows Server 2012, Windows Server 2012 R2, Windows Server 2016, Windows Server 2019, Windows Server 2022
  8. Install the AD module on PowerShell Core 6.x on a Windows computer
  9. Use the Active Directory module on Linux and macOS
  10. All versions: Import the ActiveDirectory module remotely
    • Create an interactive remote session
    • Import the AD module from a remote session
    • Export the remote AD module to a local module
  11. PowerShell Core and Windows PowerShell modules
  12. Conclusion
  • Author
  • Recent Posts

Michael Pietroforte is the founder and editor in chief of 4sysops. He has more than 35 years of experience in IT management and system administration.

Also read: How to install the PowerShell 7 Active Directory module.

The installation of the AD module varies significantly for the different Windows and PowerShell versions. At the time of this writing, the AD module that comes with RAST does not work with PowerShell Core 6.0. However, this guide explains how you can manage Active Directory from PowerShell Core even on macOS and Linux.

Windows 7

On a Windows 7 computer, you can follow this procedure to install the Active Directory module:

  1. Download the Remote Server Administration Tools (RSAT) for Windows 7.
  2. Open the Control Panel, start typing features, and then click Turn Windows features on or off.
  3. Scroll down to Remote Server Administration Tools and enable the Active Directory Module for Windows PowerShell in Remote Server Administration Tools > Role Administration Tools > AD DS and AD LDS Tools.
  4. Run Import-Module ActiveDirectory on a PowerShell console.

Active Directory Module for Windows PowerShell on Windows 7

Active Directory Module for Windows PowerShell on Windows 7

If the Windows 7 machine only has PowerShell 2.0 installed, you have to add the Import-Module ActiveDirectory command to your profile because PowerShell doesn’t load modules automatically. For instance, you can import the module in %UserProfile%My DocumentsWindowsPowerShellprofile.ps1. Makes sure you’ve set your execution policy to either RemoteSigned or Unrestricted: Set-ExecutionPolicy RemoteSigned.

Another option is to open the module from the Administrative Tools folder in the Control Panel.

Active Directory Module in Administrative Tools

Active Directory Module in Administrative Tools

Windows Server 2008 R2

If your Windows Server 2008 R2 machine is a domain controller, the PowerShell Active Directory Module is already installed. You only have to install the module on member servers. The procedure on Windows Server 2008 R2 is similar to that on Windows 7. (Note that the module is not available for Windows Server 2008.)

One difference is that you don’t have to download RSAT because the tools are already available on Windows Server 2008 R2.

  1. In Server Manager, click Add features, and then:
  2. Select Active Directory module for Windows PowerShell in Remote Server Administration Tools > Role Administration Tools > AD DS and AD LDS Tools.

Alternatively, you can install the module from a PowerShell console:

Import-Module ServerManagerAdd-WindowsFeature RSAT-AD-PowerShell

After copying the module to your computer, you have to import it:

Import-Module ActiveDirectory

Or you can right-click the PowerShell icon on the taskbar and select Import system modules.

Import system modules

Import system modules

As on Windows 7, if you want to make the import permanent, you have to add the above import command to your PowerShell profile. Notice this description assumes you haven’t updated PowerShell 2 on your Windows Server 2008 R2 machine (see the description about Windows 7).

Windows 8, Windows 8.1

Things are a lot easier in Windows 8, Windows 8.1, and Windows 10. All you have to do is download and install RSAT (Windows 8, Windows 8.1, Windows 10). The installation enables all tools by default, and you also don’t have to import the module. You can use the AD module right away after you install RSAT.

Windows 10

Since Windows 10, the RSAT tools were shifted from being a standalone package to being a feature on demand in Windows 10. Click the menu and then search for «features» and then navigate to App and Features > Optional Features > Add a feature. Type RSAT in the search field and select the second option—RSAT: Active Directory Domain Services and Lightweight Directory Services Tools.

Install the AD module in Windows 10

Install the AD module in Windows 10

Windows 11

In Windows 11, click the Start, type «Settings» in the Search field.

Apps in Windows 11

Apps in Windows 11

Now click Apps > Optional Features > View features.

Optinal Features in Windows 11

Optinal Features in Windows 11

Add an optional feature in Windows 11

Add an optional feature in Windows 11

Then type «RSAT» and select RSAT: Active Directory Domain Services and Lightweight Directory Services Tools and click Next and then Install.

Install RSAT on Windows 11

Install RSAT on Windows 11

To verify that RSAT has been installed launch a PowerShell console with Administrator privileges and then type this command:

Get-WindowsCapability -Name RSAT* -Online | Select-Object -Property DisplayName, State

Verfiying that RSAT is installed with PowerShell

Verfiying that RSAT is installed with PowerShell

On Windows 11 with PowerShell

If you don’t want to avoid all this clicking you can install all the RSAT tools in one go with this PowerShell command below. Make sure that you are working on an elevated PowerShell console.

Get-WindowsCapability -Name RSAT* -Online | Add-WindowsCapability -Online

Intstall RSAT with PowerShell

Intstall RSAT with PowerShell

Windows Server 2012, Windows Server 2012 R2, Windows Server 2016, Windows Server 2019, Windows Server 2022

As on Windows Server 2008 R2, the AD module is already installed on domain controllers on Windows Server 2012, Windows Server 2012 R2, and Windows Server 2016. On member servers, you can add the module as a feature in Server Manager.

  1. Start Server Manager.
  2. Click Manage > Add Roles and Features.
  3. Click Next until you reach Features.
  4. Enable Active Directory module for Windows PowerShell in Remote Server Administration Tools > Role Administration Tools > AD DS and AD LDS Tools.

Install the AD module on Windows Server 2016

Install the AD module on Windows Server 2016

Alternatively, you can install the module from a PowerShell console:

Install-WindowsFeature RSAT-AD-PowerShell

Installing the AD module on Windows Server 2012 with PowerShell

Installing the AD module on Windows Server 2012 with PowerShell

There’s no need to import the Server Manager module first, as on Windows Server 2008 R2. You also don’t have to import the AD module after the installation.

If you want to verify the successful installation of the module, you can just run the Get-ADuser cmdlet.

Install the AD module on PowerShell Core 6.x on a Windows computer

  1. Install RSAT with the method matching to your operating system (see sections above).
  2. Install the WindowsCompatibility module.
    Install-Module -Name WindowsCompatibility
  3. Load the WindowsCompatibility module like usual with the Import-Module cmdlet
    Import-Module -Name WindowsCompatibility
  4. Load the ActiveDirectory module with the Import-WinModule cmdlet
    Import-WinModule -Name ActiveDirectory

Use the Active Directory module on Linux and macOS

On Linux and macOS you can’t install Active Directory module. However, you use PowerShell remoting to connect to a Windows server with Active Directory and then work with the AD module in remoting session. Read ahead to learn how to use remoting with the AD module.

All versions: Import the ActiveDirectory module remotely

Create an interactive remote session

The simplest option is to create an interactive remote session to your domain controller with the Enter-PSsession cmdlet:

Enter-PSsession MyDomainConroller

You can then work right away with the AD cmdlets. This option is good if you only occasionally manage AD on a PowerShell console and if you don’t have to execute local scripts.

Managing Active Directory on PowerShell Core in an interactive remote session

Managing Active Directory on PowerShell Core in an interactive remote session

Import the AD module from a remote session

The second option uses implicit remoting and allows you to run the AD cmdlets from a local session. However, you execute the AD cmdlets remotely on a domain controller. In practice, you won’t notice much of difference in locally installed cmdlets. To import the AD module on PowerShell Core 6.0, execute these commands:

$S = New-PSSession -ComputerName MyDomainConroller
Import-Module -PSsession $S -Name ActiveDirectory

Import the AD module on PowerShell Core 6.0

Import the AD module on PowerShell Core 6.0

The first command creates a PowerShell session (PSsession) on the domain controller (replace MyDomainController with the name of your DC) and establishes a persistent connection. Next, we import the ActiveDirectory module from this remote PSsession into our local session.

You can now use all AD module cmdlets on your local PowerShell Core console. Just keep in mind the commands always execute remotely.

If you often work with AD, you can add the above commands to your profile, for instance in DocumentsPowerShellProfile.ps1.

Export the remote AD module to a local module

Alternatively, you can export the AD cmdlets from a remote session to a local module:

$S = New-PSSession -ComputerName MyDomainController
Export-PSsession -Session $S -Module ActiveDirectory -OutputModule RemoteAD
Remove-PSSession -Session $S
Import-Module RemoteAD

Exporting the Active Directory module to a local module

Exporting the Active Directory module to a local module

These commands will create a local module in your Documents folder under PowerShellModulesRemoteAD. However, like with the above solution, you will be working with implicit remoting, and all cmdlets will execute remotely. The local RemoteAD module only links to the cmdlets on the domain controller. If you want to use the RemoteAD module on other machines with PowerShell Core, simply copy the RemoteAD folder to the PowerShell Core module folder on the second machine.

The difference with the «import solution» is that in the «export solution,» PowerShell only establishes a connection to the domain controller when you use an AD cmdlet the first time. You also don’t have to add the above commands to your profile because PowerShell will load the local RemoteAD module automatically. However, the downside to this option is you might have to repeat the procedure after updating the AD module on the domain controller.

PowerShell Core and Windows PowerShell modules

Note that you can use Windows PowerShell together with PowerShell Core on the same machine and work with the different AD modules in both shells. If you installed RSAT, the AD module for Windows PowerShell will reside in this folder:

$env:windir/System32/WindowsPowerShell/v1.0/Modules/ActiveDirectory

If you used the export solution, the RemoteAD module will be in this folder:

$env:userprofile/Documents/PowerShell/Modules/RemoteAD

PowerShell Core and Windows PowerShell use different folders

PowerShell Core and Windows PowerShell use different folders

PowerShell Core does not import modules in WindowsPowerShell folders, and Windows PowerShell does not load PowerShell Core modules, which are always in PowerShell folders. Thus, you don’t have to worry about conflicts between the different AD modules in PowerShell Core and Windows PowerShell.

Conclusion

Using the Active Directory module has become simpler with each PowerShell version up to Microsoft’s release of PowerShell Core 6.0. However, working with implicit remoting and remote sessions has various advantages. One advantage is that you can use disconnected remote sessions. This allows you to start a script, shut down your client computer, and retrieve the results from the remote machine later. If you often work with remote sessions, you should become familiar with the different ways you can use PowerShell remote sessions. Once you get used to working with remoting, you probably won’t miss the local AD module for PowerShell Core.

Модуль Active Directory для Windows PowerShell — один из основных инструментов для администрирования домена, управления объектами в Active Directory и получения различной информации о компьютерах AD, пользователях, группах и т. д. Любой администратор Windows должен знать, как использовать как графическую оснастку AD (обычно это ADUC — Active Directory Users & Computers) и командлеты модуля RSAT-AD-PowerShell для выполнения повседневных задач администрирования Active Directory. В этой статье мы рассмотрим, как установить модуль PowerShell Active Directory в Windows, познакомимся с его основными функциями и популярными командлетами, которые полезны для управления и взаимодействия с AD.

Установка модуля Powershell Active Directory на Windows Server

Active Directory для Windows PowerShell уже встроен в операционные системы Windows Server (начиная с Windows Server 2008 R2), но по умолчанию не включен.

В Windows Server 2016, 2019 и 2022 вы можете установить модуль AD для PowerShell из Диспетчера серверов (Добавить роли и компоненты → Функции → Инструменты удалённого администрирования сервера → Инструменты администрирования ролей → Инструменты AD DS и AD LDS → Модуль Active Directory для Windows PowerShell).

В англоязычной версии сервера это соответственно в Server Manager: Add Roles and Features → Features → Remote Server Administration Tools → Role Administration Tools → AD DS and AD LDS Tools → Active Directory module for Windows PowerShell.

Если вы уже установили роль Active Directory Domain Services, то это означает, что модуль Powershell Active Directory уже активирован и дополнительных действий предпринимать не нужно.

Смотрите также: Полное руководство по Active Directory, от установки и настройки до аудита безопасности. Ч. 4: Установка Active Directory Domain Services в Windows Server 2022

Вы также можете установить модуль из консоли PowerShell с помощью команды:

Install-WindowsFeature -Name "RSAT-AD-PowerShell" -IncludeAllSubFeature

Смотрите также: Управление ролями и функциями Windows Server с помощью PowerShell

Вы можете установить RSAT-AD-PowerShell не только на контроллеры домена. Подойдёт любой рядовой сервер домена или даже рабочая станция. Модуль PowerShell Active Directory устанавливается автоматически при развёртывании роли доменных служб Active Directory (AD DS) (при повышении уровня сервера до контроллера домена AD).

Модуль взаимодействует с AD через веб-службу Active Directory, которая должна быть установлена на вашем контроллере домена (связь осуществляется через TCP-порт 9389).

Как установить модуль Active Directory PowerShell в командной строке

Вы можете установить модуль RSAT-AD-PowerShell не только на Windows Server, но и на свои рабочие станции.

Если вы попытаетесь выполнить приведённую выше PowerShell команду:

Install-WindowsFeature -Name "RSAT-AD-PowerShell" -IncludeAllSubFeature

то получите сообщение об ошибке:

Install-WindowsFeature: Целевым объектом указанного командлета не может быть клиентская операционная система Windows.

Причём независимо от того, какая у вас редакция Windows: Home, Pro, Enterprise.

Тем не менее, в Windows 10 build 1809 или новее пакет RSAT интегрирован в образ Windows (как компоненты по запросу), поэтому вы можете использовать эту команду PowerShell для установки модуля Active Directory:

Add-WindowsCapability -online -Name "Rsat.ActiveDirectory.DS-LDS.Tools"

Предыдущую команду нужно выполнять в командной строке с правами администратора.

Связанная статья: Как запустить PowerShell с правами администратора

Как установить модуль Active Directory PowerShell в Windows 11 в графическом интерфейсе

Для установки модуля Active Directory PowerShell в графическом интерфейсе в Windows 11 откройте «Settings» (Параметры), для этого нажмите Win+i и выберите вкладку «Apps» (Приложения), а затем перейдите в «Optional Features» (Дополнительные компоненты).

Теперь выберите «View features» (Просмотр компонентов) в строке «Add an optional feature» (Добавить компонент).

Для установки средств удалённого администрирования Active Directory найдите «RSAT: Active Directory Domain Services and Lightweight Directory Services Tools» (Средства удалённого администрирования сервера: средства доменных служб Active Director и служб облегчённого доступа к каталогам), поставьте галочку и нажмите на кнопку «Next» (Далее),

затем нажмите «Install» (Установить).

Примечание: если при поиске того или иного компонента вы не можете его найти, то, возможно, данный компонент уже установлен.

Чтобы в этом убедиться в строке поиска под надписью «Installed features» (Установленные компоненты) введите название искомого компонента.

Также помните, что в английской и локализованных версиях Windows данные компоненты называются по-разному!

Как установить модуль Active Directory PowerShell в Windows 10 в графическом интерфейсе

Для установки модуля Active Directory PowerShell в графическом интерфейсе, нажмите Win+x, затем в открывшемся меню выбираем «Apps and Features» (Приложения и возможности).

Далее выбираем «Optional Features» (Дополнительные компоненты).

Теперь выбираем «Add a feature» (Добавить компонент).

Для установки средств удалённого администрирования Active Directory выбираем «RSAT: Active Directory Domain Services and Lightweight Directory Services Tools» (Средства удалённого администрирования сервера: средства доменных служб Active Director и служб облегчённого доступа к каталогам) и нажимаем на кнопку «Install» (Установить).

Командлеты Active Directory PowerShell

В модуле Active Directory для Windows PowerShell есть множество командлетов для взаимодействия с AD. Каждая новая версия RSAT содержит больше командлетов, чем предыдущая. В Windows Server 2022 доступно 147 командлетов PowerShell для Active Directory.

Перед использованием командлетов модуля Active Directory вам необходимо импортировать его в сеанс PowerShell:

Import-Module ActiveDirectory

Начиная с Windows Server 2012 R2, Windows 8.1 и в последующих версиях модуль импортируется автоматически.

Если модуль Active Directory не установлен на вашем компьютере, вы можете импортировать его со своего контроллера домена (для этого вам нужны права администратора домена) или с другого настольного компьютера:

$psSess = New-PSSession -ComputerName ИМЯ_КОМПЬЮТЕРА
Import-Module -PSsession $psSess -Name ActiveDirectory

В этих командах ИМЯ_КОМПЬЮТЕРА — это компьютер, который является Контроллером Домена, либо компьютером, на котором установлен модуль Powershell Active Directory.

Вы можете отобразить полный список доступных командлетов Active Directory с помощью команды:

Get-Command -module ActiveDirectory

Чтобы посчитать общее количество командлетов в модуле AD выполните команду:

Get-Command -module ActiveDirectory | measure-object | select count

Большинство командлетов RSAT-AD-PowerShell начинаются с префиксов Get-, Set- или New-.

  • Командлеты Get- класса используются для получения различной информации из Active Directory (Get-ADUser — свойства пользователя, Get-ADComputer — настройки компьютера, Get-ADGroupMember — членство в группе и так далее). Чтобы запустить их, вам не нужно быть администратором домена. Любой пользователь домена может запускать команды PowerShell для получения значений атрибутов объекта AD (кроме конфиденциальных, как в примере с LAPS);
  • Командлеты класса Set- используются для установки (изменения) параметров объекта в Active Directory. Например, вы можете изменить свойства пользователя (Set-ADUser), настройки компьютера (Set-ADComputer), добавить пользователя в группу и так далее. Для этого у вашей учётной записи должны быть разрешения на изменение свойств объекта;
  • Команды, начинающиеся с New- позволяют создавать объекты AD (создать пользователя – New-ADUser, создать группу – New-ADGroup);
  • Командлеты Remove- используются для удаления объектов AD.

Так вы можете получить помощь по любому командлету:

Get-Help КОМАНДЛЕТ
Get-Help КОМАНДЛЕТ -Full

Смотрите также: Как получить справку по командам PowerShell

Вы можете отобразить примеры использования командлетов Active Directory следующим образом:

(Get-Help КОМАНДЛЕТ).examples

Или:

Get-Help КОМАНДЛЕТ -Examples

Всплывающие подсказки удобно использовать при вводе параметров командлета в PowerShell ISE.

Администрирование Active Directory с помощью модуля RSAT-AD-PowerShell

Давайте посмотрим на некоторые типичные задачи администратора, которые вы можете выполнять с помощью командлетов Active Directory для PowerShell.

Вы можете найти больше полезных примеров использования командлетов PowerShell для AD на веб-сайте pwsh.ru. Чтобы получить подробные инструкции и примеры использования, переходите по ссылкам, присутствующим в кратком описании каждого командлета.

New-ADUser: создание пользователей AD

Чтобы создать нового пользователя AD, вы можете использовать командлет New-ADUser. Вы можете создать пользователя с помощью следующей команды:

New-ADUser -Name "Mila Beck" -GivenName "Mila" -Surname "Beck" -SamAccountName "mbeck" -UserPrincipalName "mbeck@hackware.ru" -Path "OU=Users,OU=Berlin,OU=DE,DC=ds,DC=hackware,DC=ru" -AccountPassword(Read-Host -AsSecureString "Input User Password") -Enabled $true

Get-ADComputer: получение свойств компьютера

Чтобы отобразить информацию о свойствах компьютера в конкретном подразделении (имя компьютера и дата последнего входа в систему), используйте командлет Get-ADComputer:

Get-ADComputer -SearchBase 'OU=CA,OU=USA,DC=ds,DC=hackware,DC=ru' -Filter * -Properties * | FT Name, LastLogonDate -Autosize

Смотрите также «Get-ADComputer: поиск сведений о компьютерах и фильтр компьютеров по их свойствам в Active Directory».

Add-AdGroupMember: добавить пользователя AD в группы

Чтобы добавить пользователей в существующую группу безопасности в вашем домене AD, выполните эту команду:

Add-AdGroupMember -Identity LondonSales -Members e.braun, l.wolf

Отобразить список пользователей в группе AD и экспортировать его в файл CSV:

Get-ADGroupMember LondonSales -recursive | ft samaccountname | Out-File c:psexport_ad_users.csv

В предыдущей команде «ft» это командлет Format-Table.

Смотрите также: Управление группами Active Directory с помощью PowerShell

Set-ADAccountPassword: сброс пароля пользователя в AD

Чтобы сбросить пароль пользователя AD из PowerShell, выполните следующую команду:

Set-ADAccountPassword m.lorenz -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "Ne8Pa$$0rd1" -Force -Verbose) -PassThru

Как разблокировать, включить и отключить учётную запись AD?

Чтобы отключить учётную запись пользователя AD:

Disable-ADAccount m.lorenz

Чтобы включить учётную запись:

Enable-ADAccount m.lorenz

Чтобы разблокировать учётную запись после того, как она была заблокирована политикой паролей домена:

Unlock-ADAccount m.lorenz

Search-ADAccount: как найти неактивные и отключённые объекты?

Чтобы найти и отключить все компьютеры в домене AD, которые не входили в систему более 90 дней, используйте командлет Search-ADAccount:

$timespan = New-Timespan -Days 90
Search-ADAccount -AccountInactive -ComputersOnly -TimeSpan $timespan | Disable-ADAccount

New-ADOrganizationalUnit: создание организационной единицы в AD

Чтобы быстро создать типичную структуру организационной единицы в AD, вы можете использовать сценарий PowerShell. Предположим, вы хотите создать несколько подразделений с именами состояний и создать в них типичные контейнеры объектов. Создание этой структуры AD вручную с помощью графической оснастки ADUC занимает довольно много времени. Модуль AD для PowerShell позволяет сделать это за секунды (кроме времени на написание скрипта):

$fqdn = Get-ADDomain
$fulldomain = $fqdn.DNSRoot
$domain = $fulldomain.split(".")
$Dom = $domain[0]
$Ext = $domain[1]
$Sites = ("Nevada","Texas","California","Florida")
$Services = ("Users","Admins","Computers","Servers","Contacts","Service Accounts")
$FirstOU ="USA"
New-ADOrganizationalUnit -Name $FirstOU -Description $FirstOU -Path "DC=$Dom,DC=$EXT" -ProtectedFromAccidentalDeletion $false
ForEach-Object ($S in $Sites)
{
	New-ADOrganizationalUnit -Name $S -Description "$S" -Path "OU=$FirstOU,DC=$Dom,DC=$EXT" -ProtectedFromAccidentalDeletion $false
	ForEach-Object ($Serv in $Services)
	{
		New-ADOrganizationalUnit -Name $Serv -Description "$S $Serv" -Path "OU=$S,OU=$FirstOU,DC=$Dom,DC=$EXT" -ProtectedFromAccidentalDeletion $false
	}
}

После запуска сценария в Active Directory появляется следующая структура подразделений.

Move-ADObject: перемещение объектов между контейнерами AD

Чтобы перемещать объекты между контейнерами AD, вы можете использовать командлет Move-ADObject:

$TargetOU = "OU=Sales,OU=Computers,DC=ds,DC=hackware,DC=ru"
Get-ADComputer -Filter 'Name -like "SalesPC*"' | Move-ADObject -TargetPath $TargetOU

Get-ADReplicationFailure: проверка сбоев репликации AD

Используя командлет Get-ADReplicationFailure, вы можете проверить состояние репликации между контроллерами домена AD:

Get-ADReplicationFailure -Target NY-DC01,NY-DC02

Get-ADDomainController: Получение информации о контроллерах домена

Чтобы получить информацию обо всех контроллерах домена в домене, используйте командлет Get-AdDomainController:

Get-ADDomainController -filter * | select hostname,IPv4Address,IsGlobalCatalog,IsReadOnly,OperatingSystem | format-table -auto

Итак, мы рассмотрели основные возможности модуля Active Directory PowerShell для администрирования домена AD. Я надеюсь, что это побудит вас продолжить изучение других функций модуля и автоматизировать большую часть задач управления AD.

Связанные статьи:

  • Как установить Active Directory Domain Services с помощью PowerShell (65.1%)
  • Get-ADComputer: поиск сведений о компьютерах и фильтр компьютеров по их свойствам в Active Directory (64.7%)
  • Как определить причину блокировки учётной записи в домене Active Directory (63.5%)
  • Управление группами Active Directory с помощью PowerShell (60.2%)
  • Снижение уровня контроллеров домена в Windows Server в PowerShell и графическом интерфейсе (56.1%)
  • LAPS: управление паролями локальных администраторов на компьютерах домена (RANDOM — 54.5%)

Сегодня мы научимся устанавливать средства удаленного администрирования сервера на примере модуля Active Directory для Windows PowerShell, все это мы будем делать в операционной системе Windows Server 2016.

Содержание

  1. Что такое RSAT?
  2. Установка модуля Active Directory для Windows PowerShell
  3. Установка модуля RSAT-AD-PowerShell с помощью мастера
  4. Шаг 1
  5. Шаг 2
  6. Шаг 3
  7. Шаг 4
  8. Шаг 5
  9. Шаг 6
  10. Шаг 7
  11. Установка модуля RSAT-AD-PowerShell с помощью PowerShell
  12. Смотрим список командлетов PowerShell для работы с Active Directory

RSAT или Remote Server Administration Tools – это средства удаленного администрирования сервера, которые предназначены для управления ролями и компонентами сервера. В состав RSAT входят и необходимые оснастки управления, и утилиты командной строки и модули Windows PowerShell. Вы можете установить все это сразу, а можете только то, что Вам нужно.

Если Вы хотите установить средства удаленного администрирования сервера на клиентскую операционную систему, то Вам предварительно необходимо скачать их с официального сайта Microsoft.

В серверных операционных систем они поставляются в виде компонента, и сегодня мы научимся устанавливать RSAT в Windows Server 2016.

Установка модуля Active Directory для Windows PowerShell

По умолчанию в системе установлены не все модули Windows PowerShell, некоторые из них добавляются во время установки соответствующей роли или компонента. Например, если Ваш сервер не является контроллером домена, соответствующего модуля PowerShell (RSAT-AD-PowerShell) для администрирования Active Directory в нем нет, т.е. использовать командлеты PowerShell для управления AD Вы не сможете. Однако Вы можете установить модуль PowerShell для работы с Active Directory. Именно это мы сейчас и рассмотрим, при этом я покажу два варианта установки модуля RSAT-AD-PowerShell — это с помощью «Мастера добавления ролей и компонентов», т.е. используя графический интерфейс и, конечно же, с помощью Windows PowerShell.

Процесс установки модуля Active Directory для Windows PowerShell такой же, как и установка остальных компонентов и средств удаленного администрирования в Windows Server 2016, поэтому если Вы умеете устанавливать роли или компоненты сервера, то с установкой RSAT-AD-PowerShell Вы легко справитесь.

Шаг 1

Запускаем «Диспетчер серверов» и нажимаем «Управление ->Добавить роли или компоненты».

Скриншот 1

Шаг 2

На первом окне можем сразу нажать «Далее».

Скриншот 2

Шаг 3

Далее выбираем тип установки, мы хотим установить компонент, поэтому выбираем первый пункт «Установка ролей или компонентов», жмем «Далее».

Скриншот 3

Шаг 4

Затем выбираем сервер, на который будут установлены роли и компоненты, жмем «Далее».

Скриншот 4

Шаг 5

На этом шаге нам предлагают выбрать роли для установки, а так как мы не собираемся устанавливать роли, сразу жмем «Далее».

Скриншот 5

Курс по SQL для начинающих

Шаг 6

На шаге выбора компонентов мы ищем пункт «Средства удаленного администрирования сервера -> Средства администрирования ролей -> Средства AD DS и AD LDS -> Модуль Active Directory для Windows PowerShell» и отмечаем его галочкой, жмем «Далее».

Скриншот 6

Шаг 7

Проверяем выбор компонентов и жмем «Установить».

Скриншот 7

Начнется процесс установки модуля Active Directory для Windows PowerShell.

Скриншот 8

Он будет завершен, когда мы увидим сообщение «Установка выполнена на …», нажимаем «Закрыть».

Скриншот 9

Если Вы не хотите щелкать мышкой по окошкам мастера, то Вы можете легко выполнить процедуру установки компонентов с помощью нашего любимого Windows PowerShell, кстати, таким способом это делается, на мой взгляд, гораздо проще и быстрей.

Для установки модуля Active Directory для Windows PowerShell запустите оболочку PowerShell и выполните следующие команды (вместо командлета Add-WindowsFeature можно использовать Install-WindowsFeature).

  
  Import-Module ServerManager 
  Add-WindowsFeature -Name "RSAT-AD-PowerShell" –IncludeAllSubFeature

Скриншот 10

Смотрим список командлетов PowerShell для работы с Active Directory

Для того чтобы проверить, что у нас установился необходимый модуль PowerShell давайте, выполним команды, которые покажут нам количество командлетов для работы с Active Directory и сам список этих командлетов.

Чтобы узнать, сколько у нас командлетов для администрирования Active Directory пишем вот такую команду

  
  Get-Command -Module ActiveDirectory | Measure-Object

А для того чтобы посмотреть полный перечень командлетов пишем следующую команду, т.е. результат работы Get-Command мы не передаем по конвейеру командлету Measure-Object.

  
  Get-Command -Module ActiveDirectory

Скриншот 11

Мы видим, что нас появилось 147 командлетов для работы с Active Directory, которые мы теперь можем использовать для администрирования AD.

На этом все, надеюсь, материал был Вам полезен, удачи!

Today we’ll show you how to install and use the Windows PowerShell Active Directory Module. PowerShell AD Module is a part of the Remote Server Administration Tools (RSAT). RSAT includes all necessary management tools, command-line utilities, and Windows PowerShell modules to manage Windows Server infrastructure. You can use the RSAT-AD-PowerShell cmdlets to perform basic AD management tasks and get different information on domain users, computers, groups, and other objects. You can install RSAT-AD-PowerShell on Windows Server hosts and workstations running desktop OS versions (Windows 11, 10, 8.1, and 7).

Install PowerShell Active Directory Module on Windows Server

The Active Directory module for Windows PowerShell first appeared on Windows Server 2008 R2. It is automatically deployed on Windows Server after you installed the ADDS role (Active Directory Domain Services) when promoting a server to the domain controller. You can install this module manually on any member Windows server or workstation.

You can install the Active Directory module for Windows PowerShell on Windows Server 2019/2016/2012 R2 using the Add Roles and Features Wizard from the Server Manager. It is enough to start the wizard and at the step when selecting features, you need to select the item Remote Server Administration Tools > Role Administration Tools > AD DS and AD LDS Tools > Active Directory module for Windows PowerShell;

import-module activedirectory

You can also install this module using PowerShell. Open the PowerShell console as an administrator and run the following commands:

Import-Module ServerManager 

Add-WindowsFeature -Name "RSAT-AD-PowerShell" –IncludeAllSubFeature

powershell install active directory module windows 10

You can also use DISM to install the AD PowerShell module on Windows:

DISM /online /enable-feature /featurename:RSATClient-Roles-AD

DISM /online /enable-feature /featurename:RSATClient-Roles-AD-DS

DISM /online /enable-feature /featurename:RSATClient-Roles-AD-DS-SnapIns

To check the installation status of a module, use the command:

Get-WindowsFeature RSAT-AD-PowerShell

powershell install active directory module

Hint. If you are using the PowerShell Core 7.x (pwsh.exe), keep in mind that the Active Directory module is fully natively compatible with this version of PoSh. But first, you need to install the WindowsCompatibility module:

Install-Module -Name WindowsCompatibility

Hint. A different PowerShell module is used to manage objects in the Azure Active Directory — Azure Active Directory Module for Windows PowerShell.

Installing the AD PowerShell Module on Windows 10 and 11

In Windows 11, Windows 10, Windows 8.1, and Windows 7, to install the RSAT-AD-PowerShell module, first you must install the appropriate version of RSAT. RSAT is available for installation for Professional, Education, and Enterprise Windows editions (Windows Home or Single Language are not supported).

On modern Windows 10 builds (1809 and newer) the RSAT became a part of Features on Demand (FoD). You can install AD RSAT Tools from the Settings menu (Settings > Apps > Manage Optional Features > Add features > RSAT: Active Directory Domain Services and Lightweight Directory Tools > Install).

Or from the PowerShell console:

Add-WindowsCapability –online –Name “Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0”

install active directory powershell module

You will need to make sure that your security policies, firewalls, and proxies are allowed to access Microsoft Update servers on the Internet to download and install FOD components.

On Windows 11, you can install the Active Directory RSAT package from Settings > Apps > Optional Features > Add an optional feature > type Active Directory in the search box and select the RSAT: Active Directory Domain Services and Lightweight Directory Tools feature > Next > Install.

import-module activedirectory windows 10

Or you can install the module from the elevated PowerShell console:

Get-WindowsCapability -Name Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0 -Online | Add-WindowsCapability -Online

install-module activedirectory

You don’t have to reboot Windows after installing RSAT.

In order to RSAT module on Windows 7, 8.1, and Windows 10 (up to build 1803) you need to download and install a special MSU package See how to install Remote Server Administration Tools on Windows.

Then you need to enable the module (Control Panel > Programs > Turn Windows Features On or Off > Remote Server Administration Tools > Role Administration Tools > AD DS and AD LDS Tools > Active Directory module for Windows PowerShell).

Or using PowerShell:

Enable-WindowsOptionalFeature -Online -FeatureName RSATClient-Roles-AD-Powershell

install ad module powershell

Importing PowerShell Active Directory Module on Windows

The RSAT-AD-PowerShell module is automatically imported into your PowerShell session. However, on legacy versions of Windows (Windows 7 and Windows Server 2008 R2), you may get an error when running any cmdlet from the Active Directory PowerShell module:

Get-ADComputer: The ‘Get-ADComputer’ command was found in the module ‘ActiveDirectory’, but the module could not be loaded. For more information, run ‘Import-Module ActiveDirectory’.

In this case, you need to manually import the module into the PowerShell session with the command:

Import-Module activedirectory

powershell active directory module

Also, you can import the module from a remote computer/server (with installed RSAT-AD-PowerShell module) and import it into your PowerShell session (using the PSRemoting):

$S = New-PSSession -ComputerName MyDomainController 

Export-PSsession -Session $S -Module ActiveDirectory -OutputModule RemoteAD 

Import-Module RemoteAD -Force

Now you can use all cmdlets of the RSAT-AD-PowerShell module from a remote computer as if you had it installed locally. However, implicit remoting will actually work here, and all PowerShell cmdlets will be executed remotely.

The session will be active until you close the PowerShell console. You can also close the session (Disconnect-PSSession -Session $S) or remove it (Remove-PSSession -Session $S).

Now you can use the Active Directory module remotely without installing it on your computer.

To confirm the AD PoSh module is installed and imported to the PowerShell session on Windows, run the command:

Get-Module ActiveDirectory

powershell active directory module windows 10

You can display the list of available AD PowerShell module cmdlets for interacting with Active Directory as follows:

Get-Command -Module ActiveDirectory

powershell install ad module

Different versions of Windows (RSAT) have a different number of cmdlets available:

get-command -Module activedirectory|measure
  • Windows Server 2008 R2 — 76 cmdlets;
  • Windows Server 2012 — 135 cmdlets;
  • Windows Server 2012 R2/2016/2019/2022 — 147 cmdlets.

The following is a complete list of AD PowerShell Module cmdlets in Windows Server 2019:

Add-ADCentralAccessPolicyMember 

Add-ADComputerServiceAccount 

Add-ADDomainControllerPasswordReplicationPolicy 

Add-ADFineGrainedPasswordPolicySubject 

Add-ADGroupMember 

Add-ADPrincipalGroupMembership 

Add-ADResourcePropertyListMember 

Clear-ADAccountExpiration 

Clear-ADClaimTransformLink 

Disable-ADAccount 

Disable-ADOptionalFeature 

Enable-ADAccount 

Enable-ADOptionalFeature 

Get-ADAccountAuthorizationGroup 

Get-ADAccountResultantPasswordReplicationPolicy 

Get-ADAuthenticationPolicy 

Get-ADAuthenticationPolicySilo 

Get-ADCentralAccessPolicy 

Get-ADCentralAccessRule 

Get-ADClaimTransformPolicy 

Get-ADClaimType 

Get-ADComputer 

Get-ADComputerServiceAccount 

Get-ADDCCloningExcludedApplicationList 

Get-ADDefaultDomainPasswordPolicy 

Get-ADDomain 

Get-ADDomainController 

Get-ADDomainControllerPasswordReplicationPolicy 

Get-ADDomainControllerPasswordReplicationPolicyUsage 

Get-ADFineGrainedPasswordPolicy 

Get-ADFineGrainedPasswordPolicySubject 

Get-ADForest 

Get-ADGroup 

Get-ADGroupMember 

Get-ADObject 

Get-ADOptionalFeature 

Get-ADOrganizationalUnit 

Get-ADPrincipalGroupMembership 

Get-ADReplicationAttributeMetadata 

Get-ADReplicationConnection 

Get-ADReplicationFailure 

Get-ADReplicationPartnerMetadata 

Get-ADReplicationQueueOperation 

Get-ADReplicationSite 

Get-ADReplicationSiteLink 

Get-ADReplicationSiteLinkBridge 

Get-ADReplicationSubnet 

Get-ADReplicationUpToDatenessVectorTable 

Get-ADResourceProperty 

Get-ADResourcePropertyList 

Get-ADResourcePropertyValueType 

Get-ADRootDSE 

Get-ADServiceAccount 

Get-ADTrust 

Get-ADUser 

Get-ADUserResultantPasswordPolicy 

Grant-ADAuthenticationPolicySiloAccess 

Install-ADServiceAccount 

Move-ADDirectoryServer 

Move-ADDirectoryServerOperationMasterRole 

Move-ADObject 

New-ADAuthenticationPolicy 

New-ADAuthenticationPolicySilo 

New-ADCentralAccessPolicy 

New-ADCentralAccessRule 

New-ADClaimTransformPolicy 

New-ADClaimType 

New-ADComputer 

New-ADDCCloneConfigFile 

New-ADFineGrainedPasswordPolicy 

New-ADGroup 

New-ADObject 

New-ADOrganizationalUnit 

New-ADReplicationSite 

New-ADReplicationSiteLink 

New-ADReplicationSiteLinkBridge 

New-ADReplicationSubnet 

New-ADResourceProperty 

New-ADResourcePropertyList 

New-ADServiceAccount 

New-ADUser 

Remove-ADAuthenticationPolicy 

Remove-ADAuthenticationPolicySilo 

Remove-ADCentralAccessPolicy 

Remove-ADCentralAccessPolicyMember 

Remove-ADCentralAccessRule 

Remove-ADClaimTransformPolicy 

Remove-ADClaimType 

Remove-ADComputer 

Remove-ADComputerServiceAccount 

Remove-ADDomainControllerPasswordReplicationPolicy 

Remove-ADFineGrainedPasswordPolicy 

Remove-ADFineGrainedPasswordPolicySubject 

Remove-ADGroup 

Remove-ADGroupMember 

Remove-ADObject 

Remove-ADOrganizationalUnit 

Remove-ADPrincipalGroupMembership 

Remove-ADReplicationSite 

Remove-ADReplicationSiteLink 

Remove-ADReplicationSiteLinkBridge 

Remove-ADReplicationSubnet 

Remove-ADResourceProperty 

Remove-ADResourcePropertyList 

Remove-ADResourcePropertyListMember 

Remove-ADServiceAccount 

Remove-ADUser 

Rename-ADObject 

Reset-ADServiceAccountPassword 

Restore-ADObject 

Revoke-ADAuthenticationPolicySiloAccess 

Search-ADAccount 

Set-ADAccountAuthenticationPolicySilo 

Set-ADAccountControl 

Set-ADAccountExpiration 

Set-ADAccountPassword 

Set-ADAuthenticationPolicy 

Set-ADAuthenticationPolicySilo 

Set-ADCentralAccessPolicy 

Set-ADCentralAccessRule 

Set-ADClaimTransformLink 

Set-ADClaimTransformPolicy 

Set-ADClaimType 

Set-ADComputer 

Set-ADDefaultDomainPasswordPolicy 

Set-ADDomain 

Set-ADDomainMode 

Set-ADFineGrainedPasswordPolicy 

Set-ADForest 

Set-ADForestMode 

Set-ADGroup 

Set-ADObject 

Set-ADOrganizationalUnit 

Set-ADReplicationConnection 

Set-ADReplicationSite 

Set-ADReplicationSiteLink 

Set-ADReplicationSiteLinkBridge 

Set-ADReplicationSubnet 

Set-ADResourceProperty 

Set-ADResourcePropertyList 

Set-ADServiceAccount 

Set-ADUser 

Show-ADAuthenticationPolicyExpression 

Sync-ADObject 

Test-ADServiceAccount 

Uninstall-ADServiceAccount 

Unlock-ADAccount

Using RSAT-AD-PowerShell Module

The PowerShell AD module provides an administrator with many opportunities for interacting with Active Directory objects and automating tasks (this is especially useful when performing bulk actions aimed at a large number of AD objects). You can perform all the basic operations with the AD directory:

  • Get all AD properties and object attributes;
  • Change object properties;
  • Manage AD groups;
  • Create new directory objects, etc.

The cmdlets from the Active Directory module interact with Active Directory Web Services (ADWS) on the domain controller. This role is installed on a domain controller during the promotion from a domain member server to a domain controller. The module accesses the Active Directory Web Services via TCP port 9389 (check that this port is open on the firewall).

Hint. Check if the ADWS service is running on the domain controller and is responding on port 9389 (Test-NetConnection DC01 -port 9389). Learn more about the Unable to find a default server with Active Directory Web Services running error.

If your computer is joined to an AD domain, the AD PowerShell cmdlets find the nearest domain controller to connect to based on the LogonServer environment variable. However, you can connect to any other domain controller using the -Server parameter (available on most cmdlets). For example:

Get-ADUser a.smith -Server nydc01.theitbros.com

Let’s look at a few examples of using the cmdlets of the RSAT-AD-PowerShell module.

  • To get the list of AD domain controllers, run the command:
    Get-ADDomainController –filter *| format-table

install module active directory

  • You can create several AD users at once, you can import AD users from CSV. Use it together with the New-ADUser cmdlet.
    To get information about an AD user, use the Get-ADUser cmdlet:

    Get-ADUser –identity t.muller –properties *

    A similar cmdlet to display all computer attributes in AD:

    Get-ADComputer –identity dc01 –properties *

import ad module powershell

  • Use the New-ADGroup cmdlet to create an Active Directory group. For example, to create a new group named ItalyUsers in the specific OU, run the command:
    New-ADGroup -Path "OU=Groups,OU=Italy,DC=theitbros,DC=com" -Name "ItalyUsers" -GroupScope Global -GroupCategory Distribution
  • To get the AD group info, use the Get-ADGroup cmdlet:
    Get-ADGroup ItalyUsers
  • If you want to add a user or computer to an AD group, use the Add-ADGroupMember cmdlet:
    Add-ADGroupMember –Identity ‘NY_Managers’ -Members s.adams,d.thumb,p.muller
  • Use the New-ADOrganizationalUnit cmdlet to create an Active Directory OU:
    New-ADOrganizationalUnit -Name "France"
  • Use the Unlock-ADAccount cmdlet to unlock account in Active Directory domain:
    Get-ADUser -Identity bjackson | Unlock-ADAccount
  • Or you can use the Set-ADAccountPassword to change domain user password or reset it:
    $newPass=Read-Host "Enter the new user password" –AsSecureString
    
    Set-ADAccountPassword bjackson -NewPassword $newPass
  • Check AD replication status for all domain controllers in the specific Active Directory site:
    Get-ADReplicationFailure -scope SITE -target London | Format-Table Server, FirstFailureTime, FailureClount, LastError, Partner
  • Find and disable AD accounts that have not logged in to the domain for more than 120 days:
    Search-ADAccount -AccountInactive -TimeSpan 120 –UsersOnly| Disable-ADAccount
  • For detailed help on any cmdlet from the AD-PoSh module, use the Get-Help command:
    get-help set-aduser

install ad module powershell windows 10

If the computer is not a part of the Active Directory domain, the following warning appears when you try importing the AD-PoSh module:

WARNING: Error initializing default drive: ‘Unable to find a default server with Active Directory Web Services running’.

In this case, you need to specify the AD domain controller and user credentials to connect to it.

First of all, you need to get the user’s credentials to access the domain. Any authenticated domain user can view almost all AD objects properties (excluding protected Active Directory attributes).

$cred = Get-Credential

install active directory module powershell

For example, to get the user’s info from the DC named TOR-DC01 under saved credentials, use the command:

get-aduser postfixsrv –server nydc01 -Credential $cred

import module active directory

As you can see, you have received the AD account info.

So now you can use the PowerShell cmdlets to manage and query Active Directory.

  • About
  • Latest Posts

I enjoy technology and developing websites. Since 2012 I’m running a few of my own websites, and share useful content on gadgets, PC administration and website promotion.


ADModule

Microsoft signed DLL for the ActiveDirectory PowerShell module

Just a backup for the Microsoft’s ActiveDirectory PowerShell module from Server 2016 with RSAT and module installed. The DLL is usually found at this path: C:WindowsMicrosoft.NETassemblyGAC_64Microsoft.ActiveDirectory.Management

and the rest of the module files at this path:
C:WindowsSystem32WindowsPowerShellv1.0ModulesActiveDirectory

Usage

You can copy this DLL to your machine and use it to enumerate Active Directory without installing RSAT and without having administrative privileges.

PS C:> Import-Module C:ADModuleMicrosoft.ActiveDirectory.Management.dll -Verbose
Alt text

You can also use the Import-ActiveDirectory.ps1 (Thanks to PR by @D1iv3) to load the script using download-execute cradles and without writing the DLL to disk:

PS C:> iex (new-Object Net.WebClient).DownloadString(‘https://raw.githubusercontent.com/samratashok/ADModule/master/Import-ActiveDirectory.ps1’);Import-ActiveDirectory
Alt text

To be able to list all the cmdlets in the module, import the module as well. Remember to import the DLL first.

PS C:> Import-Module C:ADModuleMicrosoft.ActiveDirectory.Management.dll -Verbose

PS C:> Import-Module C:ADToolsADModuleActiveDirectoryActiveDirectory.psd1

PS C:> Get-Command -Module ActiveDirectory

Benefits

There are many benefits like very low chances of detection by AV, very wide coverage by cmdlets, good filters for cmdlets, signed by Microsoft etc. The most useful one, however, is that this module works flawlessly from PowerShell’s Constrained Language Mode
Alt text

Blog

https://www.labofapenetrationtester.com/2018/10/domain-enumeration-from-PowerShell-CLM.html

A prerequisite for every PowerShell Active Directory (AD) task is to import the PowerShell Active Directory module. This popular module allows administrators to query and make changes to Active Directory with PowerShell.

Discover, report and prevent insecure Active Directory account passwords in your environment with Specops’ completely free Password Auditor Pro. Download it today!

In this blog post, we’re going to dive into how to install the PowerShell Active Directory module on Windows 10. We’ll then cover how to connect to AD with PowerShell and go into the various ways you can authenticate to AD.

Before we begin, you should first be aware of the RSAT package. If you are using a workstation variant of Windows then you will need to install the Remote Server Administration Tools (RSAT) package. When using a Server variant of Windows, RSAT is available already.

Without RSAT you’ll get the annoying ‘the term Get-AD* is not recognized as the name of a cmdlet, function, script file, or operable program’ type messages when you attempt to run the commands we’ll be covering.

RSAT for Pre 1809 Windows 10

Download an RSAT package if you’re on Windows 10 pre-build 1809 from Microsoft. The install is simple and straightforward.

Learn how to find your Windows 10 build version here if you don’t know how.

Once you have installed RSAT, ensure the Active Directory Module for Windows PowerShell is enabled in Windows Features. By default, it should be already.

Enabling a feature to import the PowerShell Active Directory module
Enabling the Active Directory Module for Windows PowerShell

RSAT for post-1809 Windows 10

In versions of Windows from 1809 onwards the RSAT capabilities are available as optional features. There’s no need to download an external package.

To import the PowerShell Active Directory module, you must first install it. On Windows 10 post-1809, use the Add-WindowsCapability cmdlet. This enables the Rsat.ActiveDirectory.DS-LDS.Tools optional feature as shown below.

PS51> Add-WindowsCapability -Online -Name Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0

The above syntax was tested on Windows 10 Build 1903 and on Windows 7.

RSAT for Windows Server 2008R2 and Later

On Windows Server, use the PowerShell ServerManager module to enable the RSAT-AD-PowerShell feature in PowerShell.

PS51> Import-Module ServerManager
PS51> Install-WindowsFeature -Name RSAT-AD-PowerShell

It’s likely PowerShell will auto-import the module when installed. But if you’d like to ensure it loads properly, you can also use the Import-Module command.

To import the PowerShell Active Directory module, run Import-Module ActiveDirectory. If the module is installed in the right place, you will receive no errors.

Connecting and Authenticating

Once the ActiveDirectory module is set up, you can then use the Active Directory PowerShell cmdlets.

Although the cmdlets interact with different parts of AD, nearly all of them have common parameters. Two of those parameters are Server and Credential.

Connecting to a Specific Active Directory Domain Controller

By default, the AD cmdlets will find a domain controller for you. However, if you need to connect to a different domain controller, you can use the Server parameter.

The Server parameter isn’t mandatory. PowerShell will attempt to find a domain controller to connect to by default. The domain controller is determined by trying the following in the listed order:

  1. Use the Server property of objects passed in on the pipeline.
  2. Use the server associated with the AD PowerShell provider drive, if in use.
  3. Use the domain of the client computer.

You can connect to a specific domain controller by providing a value for the Server parameter. You can specify several different ADDS objects in different formats such as:

  • FQDN or NETBIOS name such as domain.local or DOMAIN which will be the domain name specified
  • FQDN or NETBIOS name such as server.domain.local or SERVER that will be the domain controller.
  • A fully-qualified domain controller and port such as server.domain.local:3268

Connecting to Active Directory with Alternate Credentials

By default, the Active Directory PowerShell cmdlets will use a two-step process for determining the user account to connect to AD.

  1. Use the credentials associated with the PowerShell AD provider drive, if the command is run from there.
  2. Utilizing the credentials of the logged-on user.

You can also specify alternate credentials using the Credential parameter.

The Credential parameter allows you to pass in a PSCredential object. If you provide a username, you will be prompted for a password and these credentials will be used.

You can see an example below of using the Get-AdUser cmdlet using an alternate credential.

PS51> $credential = Get-Credential
PS51> Get-Aduser -Filter * -Credential $credential

Want to quickly check your Active Directory for leaked passwords? Specops has a tool that does so for free and generates a nice report as well.

You also have two possible authentication types available, controlled by the AuthType parameter. These types are Negotiate (the default) and Basic. Basic authentication is only possible over an SSL connection.

PS51> Get-Aduser -Filter * -Credential $credential -AuthType Negotiate|Basic

Summary

To import the PowerShell Active Directory module is a straightforward and common process. Using the instructions provided in this article, you should be well on your way to automating all the Active Directory things!

Further Reading

  • 32 Active Directory Scripts to Automate Anything

 Windows OS Hub / PowerShell / How to Install the PowerShell Active Directory Module and Manage AD?

Every Windows system administrator should be able to use not only graphical AD snap-ins (usually it is ADUC, Active Directory Users and Computers), but also PowerShell cmdlets to perform everyday Active Directory administration tasks. Most commonly, the Active Directory module for Windows PowerShell is used for domain and object management tasks (users, computers, groups). In this article, we will look at how to install theRSAT-AD-PowerShell module on Windows, discover its basic features, and popular cmdlets that are useful to manage and interact with AD.

Contents:

  • How to Install the Active Directory PowerShell Module on Windows 10 and 11?
  • Installing the RSAT-AD-PowerShell Module on Windows Server
  • Active Directory Administration with PowerShell
  • Importing Active Directory PowerShell Module from a Remote Computer
  • Common PowerShell Commands for Active Directory

How to Install the Active Directory PowerShell Module on Windows 10 and 11?

You can install the RSAT-AD PowerShell module not only on servers but also on workstations. This module is included in the RSAT (Remote Server Administration Tools) package for Windows.

In current builds of Windows 11 and Windows 10, the RSAT components are installed online as Features on Demand. You can install the module by using the command:

Add-WindowsCapability -online -Name Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0

Add-WindowsCapability: install Active Directory PowerShell module

Or through via the Settings -> Apps -> Optional features -> Add a feature -> RSAT: Active Directory Domain Services and Lightweight Directory Services Tools.

Install RSAT AD PowerShell feature on Windows

The RSAT package had to be manually downloaded and installed on previous versions of Windows. After that, you need to enable the AD module for PowerShell from the Control Panel: Programs and Features -> Turn Windows features on or off -> Remote Server Administration Tools-> Role Administration Tools -> AD DS and AD LDS Tools.

You must first install the WindowsCompatibility module to use AD cmdlets in PowerShell Core 6.x, 7.x:

Install-Module -Name WindowsCompatibility

Then load the module into your session:

Import-Module -Name WindowsCompatibility
Import-WinModule -Name ActiveDirectory

Import Active Directory to PowerShell Core 7.3 session (pwsh.exe)

Now you can use AD cmdlets in your PowerShell Core 7.x scripts.

Installing the RSAT-AD-PowerShell Module on Windows Server

On Windows Server, you can install the Active Directory Module for Windows PowerShell from the Server Manager graphical console or by using PowerShell.

You can check that the Active Directory module is installed with the command:

Get-WindowsFeature -Name "RSAT-AD-PowerShell"

If the module is missing, install it:

Install-WindowsFeature -Name "RSAT-AD-PowerShell" –IncludeAllSubFeature

Install RSAT-AD-PowerShell using powershell

To install the module through the Server Manager, go to Add Roles and Features -> Features -> Remote Server Administration Tools -> Role Administration Tools -> AD DS and AD LDS Tools -> enable the Active Directory module for Windows PowerShell.

install windows server feature: Active Directory module for Windows PowerShell

You do not need to use a local domain controller session to manage Active Directory by using the RSAT-AD PowerShell module. This module can be installed on any member server or workstation. On AD domain controllers, the module is automatically installed when the Active Directory Domain Services (AD DS) role is deployed (when the server is promoted to a DC).

The module interacts with AD through the Active Directory Web Service that must be running on your domain controller and available to clients on a TCP port 9389. Use the Test-NetConnection cmdlet to verify that this port is not blocked by a firewall on the DC:

Test-NetConnection MUN-DC1 -port 9389

Active Directory Administration with PowerShell

The Active Directory module for Windows PowerShell has a large number of cmdlets for interacting with AD. There are 147 AD PowerShell cmdlets available in the current version of the module for Windows Server 2022/Windows 11.

Check that the module is installed on the computer:

Get-Module -Name ActiveDirectory –ListAvailable

Before you can use the Active Directory module cmdlets, you must import it into your PowerShell session (starting from Windows Server 2012 R2/ Windows 8.1 the module is imported automatically).

Import-Module ActiveDirectory

Make sure that the AD module is loaded in your PowerShell session:

Get-Module

check if ad powershell module is loaded into session

You can display a complete list of available Active Directory cmdlets:

Get-Command –module ActiveDirectory

The total number of cmdlets in the AD module:

Get-Command –module ActiveDirectory |measure-object|select count

Get all Command of ActiveDirectory powershell module

Most of the RSAT-AD PowerShell module cmdlets begin with the Get-, Set- or New- prefixes.

  • Get– class cmdlets are used to get different information from Active Directory (Get-ADUser — user properties, Get-ADComputer – computer settings, Get-ADGroupMember — group membership, etc.). You do not need to be a domain administrator to use these cmdlets. Any domain user can run PowerShell commands to get the values of the AD object attributes (except confidential ones, like in the example with LAPS);
  • Set- class cmdlets are used to set (change) object properties in Active Directory. For example, you can change user properties (Set-ADUser), computer settings (Set-ADComputer), etc. To perform these actions, your account must have write permissions on the objects you want to modify (see the article How to Delegate Administrator Privileges in Active Directory);
  • Commands that start with New- allow you to create AD objects (create a user — New-ADUser, create a group — New-ADGroup , create an Organizational Unit —  New-ADOrganizationalUnit );
  • Cmdlets starting with Add-: add a user to a group (Add-ADGroupMember), add a Fine-Grained Password Policy (Add-ADFineGrainedPasswordPolicySubject);
  • Remove- cmdlets are used to delete AD objects Remove-ADGroup, Remove-ADComputer, Remove-ADUser).

There are specific PowerShell cmdlets that you can use to manage only certain AD components:

  • Enable-ADOptionalFeature – enable optional AD features (for example, AD Recycle Bin to restore deleted objects);
  • Install-ADServiceAccount – configure managed service account (MSA, gMSA);
  • Search-ADAccount – allows you to find disabled, inactive, locked user and computer accounts in Active Directory;
  • Enable-ADAccount / Disable-ADAccount / Unlock-ADAccount – enable/disable/unlock an account.

By default, the PowerShell cmdlets connect to the nearest domain controller in your environment (LOGONSERVER). With the -Server parameter, you can connect to ADDS on a different domain controller or in a different domain (you can display a list of DCs in another domain using the nltest /dclist:newad.com command).

The -Server parameter is available for nearly all of the module cmdlets. For example

Get-ADuser j.smith -Server mun-dc1.woshub.com

You can also use the -Credential parameter to specify alternative Active Directory user credentials.

$creds = Get-Credential
Get-ADUser -Filter * -Credential $creds

Here is how you can get help on any cmdlet

get-help Set-ADUser

You can display the examples of using Active Directory cmdlets as follows:

(get-help New-ADComputer).examples

Importing Active Directory PowerShell Module from a Remote Computer

It is not necessary to install the AD PowerShell module on all computers. An administrator can remotely import this module from a domain controller (domain administrator privileges are required) or from any other computer.

PowerShell Remoting is used to connect to a remote computer. This requires that Windows Remote Management (WinRM) is enabled and configured on the remote host.

Create a new session with the remote computer that has the AD PowerShell module installed:

$psSess = New-PSSession -ComputerName DC_or_Comp_with_ADPosh

Import the ActiveDirectory module from the remote computer into your local PS session:

Import-Module -PSsession $psSess -Name ActiveDirectory

Now you can run any commands from the Active Directory module on your computer as if the module was installed locally. However, they will be executed on a remote host.

You can add these commands to your PowerShell profile file to automatically import the module from the remote session when you start the powershell.exe console. Run the notepad $profile.CurrentUserAllHosts to open your PS profile file.

You can end a remote session with the command :

Remove-PSSession -Session $psSess

This method of importing the AD module through PowerShell implicit remoting allows you to use PowerShell cmdlets from Linux and MacOS hosts that cannot install a local copy of the module.

You can also use the Active Directory Module for PowerShell without installing RSAT. To do

this, simply copy some files from a computer where the RSAT-AD PowerShell module is installed:

  • Directory C:WindowsSystem32WindowsPowerShellv1.0Modules
  • File ActiveDirectory.Management.dll
  • File ActiveDirectory.Management.resources.dll

Then you need to import the module into your current session:

Import-Module C:PSADmoduleMicrosoft.ActiveDirectory.Management.dll
Import-Module C:PSADmoduleMicrosoft.ActiveDirectory.Management.resources.dll

After that, you can use all of the AD module cmdlets without installing RSAT.

Common PowerShell Commands for Active Directory

Let’s take a look at some typical administrative tasks that can be performed using the Active Directory for PowerShell cmdlets.

You can find some useful examples of how to use Active Directory for PowerShell module cmdlets on the WOSHub website. Follow the links to get detailed instructions.

New-ADUser: Creating AD Users

To create a new AD user, you can use the New-ADUser cmdlet. You can create a user with the following command:

New-ADUser -Name "Mila Beck" -GivenName "Mila" -Surname "Beck" -SamAccountName "mbeck" -UserPrincipalName "mbeck@woshub.com" -Path "OU=Users,OU=Berlin,OU=DE,DC=woshub,DC=com" -AccountPassword(Read-Host -AsSecureString "Input User Password") -Enabled $true

For detailed info about the New-ADUser cmdlet (including an example on how to create user domain accounts in bulk), see this article.

Get-ADComputer: Getting Computer Object Properties

To get the properties of computer objects in a particular OU (the computer name and the last logon date), use the Get-ADComputer cmdlet:

Get-ADComputer -SearchBase ‘OU=CA,OU=USA,DC=woshub,DC=com’ -Filter * -Properties * | FT Name, LastLogonDate -Autosize

Add-ADGroupMember: Add Active Directory Users to Group

To add users to an existing security group in an AD domain, run this command:

Add-AdGroupMember -Identity LondonSales -Members e.braun, l.wolf

Display the list of users in the AD group and export it to a CSV file:

Get-ADGroupMember LondonSales -recursive| ft samaccountname| Out-File c:psexport_ad_users.csv

Learn more about managing AD groups with PowerShell.

Set-ADAccountPassword: Reset a User Password in AD

In order to reset a user’s password in AD with PowerShell:

Set-ADAccountPassword m.lorenz -Reset -NewPassword (ConvertTo-SecureString -AsPlainText “Ne8Pa$$0rd1” -Force -Verbose) –PassThru

How to Unlock, Enable, and Disable Active Directory Accounts?

To disable the AD user account:

Disable-ADAccount m.lorenz

To enable an account:

Enable-ADAccount m.lorenz

Unlock an account after it has been locked by a domain password policy:

Unlock-ADAccount m.lorenz

Search-ADAccount: How to Find Inactive and Disabled AD Objects?

To find and disable all computers in the AD domain that have not logged on for more than 90 days, use the Search-ADAccount cmdlet:

$timespan = New-Timespan –Days 90
Search-ADAccount -AccountInactive -ComputersOnly –TimeSpan $timespan | Disable-ADAccount

New-ADOrganizationalUnit: Create an Organizational Unit in AD

To quickly create a typical Organizational Unit structure in AD, you can use a PowerShell script. Suppose you want to create multiple OUs with states as their names and create typical object containers. It is quite time-consuming to create this AD structure manually through the graphical ADUC snap-in. AD module for PowerShell allows solving this task in seconds (except the time to write the script):

$fqdn = Get-ADDomain
$fulldomain = $fqdn.DNSRoot
$domain = $fulldomain.split(".")
$Dom = $domain[0]
$Ext = $domain[1]
$Sites = ("Nevada","Texas","California","Florida")
$Services = ("Users","Admins","Computers","Servers","Contacts","Service Accounts")
$FirstOU ="USA"
New-ADOrganizationalUnit -Name $FirstOU -Description $FirstOU -Path "DC=$Dom,DC=$EXT" -ProtectedFromAccidentalDeletion $false
foreach ($S in $Sites)
{
New-ADOrganizationalUnit -Name $S -Description "$S" -Path "OU=$FirstOU,DC=$Dom,DC=$EXT" -ProtectedFromAccidentalDeletion $false
foreach ($Serv in $Services)
{
New-ADOrganizationalUnit -Name $Serv -Description "$S $Serv" -Path "OU=$S,OU=$FirstOU,DC=$Dom,DC=$EXT" -ProtectedFromAccidentalDeletion $false
}
}

After you run the script, you will see the following OU structure in the Active Directory.

creating complex AD OU structure with New-ADOrganizationalUnit

To move objects between AD containers, you can use the Move-ADObject cmdlet:

$TargetOU = "OU=Sales,OU=Computers,DC=woshub,DC=com"
Get-ADComputer -Filter 'Name -like "SalesPC*"' | Move-ADObject -TargetPath $TargetOU

Get-ADReplicationFailure: Check Active Directory Replication

You can use the Get-ADReplicationFailure cmdlet to check the status of replication between AD domain controllers:

Get-ADReplicationFailure -Target NY-DC01,NY-DC02

To get information about all DCs in the domain, use the Get-AdDomainController cmdlet:

Get-ADDomainController –filter * | select hostname,IPv4Address,IsGlobalCatalog,IsReadOnly,OperatingSystem | format-table –auto

Get-ADDomainController - powershell get domain controller info

In this article, we looked at how to install and use the Active Directory PowerShell module for AD domain administration. I hope this article will encourage you to further explore this module and start automating most of your AD management tasks.

Понравилась статья? Поделить с друзьями:
  • Можно ли вернуть windows 7 после установки windows 10
  • Можно ли восстановить загрузчик windows 10
  • Можно ли office 2019 установить на windows 7
  • Модуль active directory для windows powershell windows 10
  • Можно ли восстановить документы после переустановки windows