Import module activedirectory windows 10

Любой системный администратор 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:\Windows\System32\WindowsPowerShell\v1.0\Modules
  • Файл ActiveDirectory.Management.dll
  • Файл ActiveDirectory.Management.resources.dll

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

Import-Module C:\path\Microsoft.ActiveDirectory.Management.dll
Import-Module C:\path\Microsoft.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:\script\export_users.csv

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

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

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

Set-ADAccountPassword apterov -Reset -NewPassword (ConvertTo-SecureString -AsPlainText “P@ssw0rd1” -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.

Для переноса объектов между контейнерами 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.

A common misconception, especially with new Windows system administrators, is they should log in to the domain controller server to manage the Active Directory. I’ve seen organizations where even the frontline service desk is allowed to log in to the domain controller servers just to provision new user accounts or create groups.

Microsoft has introduced the Remote Server Administration Tools (RSAT), allowing other computers (server or workstation) to remotely manage the Active Directory and other services running on Windows Server 2008 R2 and above. Part of the RSAT is the Active Directory PowerShell module, which administrators can use to manage the Active Directory using PowerShell cmdlets.

Stick around, and we’ll show different ways to have the Active Directory module on Windows Server and client computers.

Note. Any installation method involving the DISM module or DISM.exe installs all RSAT tools, not just the ActiveDirectory PowerShell module.

Install PowerShell Active Directory Module on Windows Server

While the Active Directory Module is automatically installed on servers with the Active Directory Domain Services (AD DS) role, it has to be installed on other servers that don’t hold the same role.

There are a few ways to install the Active Directory Module on Windows Servers, and we’ll tackle them next.

Using the Add Roles and Features Wizard (Server Manager Console)

The Server Manager console is a graphical user interface to manage the local and remote servers. It also allows administrators to install roles and features, including the Active Directory Module.

On your server, open the Server Manager.

import-module activedirectory

On the Dashboard, click “Add roles and features.”

import module active directory

When the “Add Roles and Features Wizard” window shows up, click Next until you reach the “Features” page.

Expand “Remote Server Administration Tools” → “AD DS and AD LDS Tools” and check the “Active Directory module for Windows PowerShell” box, then click Next.

powershell active directory module windows

On the Confirmation page, review the selection and click Install.

install-module activedirectory

Wait for the installation to finish and click Close.

install active directory powershell module

Using Install-WindowsFeature Cmdlet (ServerManager Module)

Installing features in the Server Manager console has a cmdlet counterpart in PowerShell called Install-WindowsFeature. This cmdlet also has an alias called Add-WindowsFeature. These cmdlets are part of the ServerManager module that’s built-in to Windows servers.

install ad module powershell

But first, let’s find out the Active Directory Module for Windows PowerShell feature status. Open Windows PowerShell as admin and run this command.

Get-WindowsFeature -Name RSAT*

As you can see below, the RSAT-AD-PowerShell feature install state is available. This status means we can install it.

import ad module powershell

Run this command to install the RSAT-AD-PowerShell feature.

Install-WindowsFeature -Name RSAT-AD-PowerShell

The screenshot below shows the result of a successful installation.

powershell active directory module

Install PowerShell Active Directory Module on Windows 10 or 11

On modern Windows 10 builds (1809 and newer), the RSAT became a part of Features on Demand (FoD). You can install RSAT directly via the Optional Features in Windows Settings, DISM.exe, and Add-WindowsCapability.

Using the Optional Features in Windows Settings

On your Windows computer, press WIN+R and run this command to open the Optional Features settings.

ms-settings:optionalfeatures

powershell install ad module

Click the “View features” button.

install module active directory

In the “Add an optional feature” window, search RSAT, check the “RSAT: Active Directory Domain Services Tools” box, and click Next.

install active directory module powershell

Click Install on the next page.

powershell import ad module

Wait for the feature to finish installing.

import active directory module

Using the Add-WindowsCapability Cmdlet (DISM Module)

Another method to install RSAT via Feature on Demand is the Add-WindowsCapability cmdlet. This cmdlet is part of the DISM module in Windows PowerShell.

Open Windows PowerShell as admin and run this command to find the RSAT feature to install.

Get-WindowsCapability -Online -Name RSAT* | Format-Table

As you can see, multiple features match. But in this instance, what we want is the Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0. Notice that the State is NotPresent, which means it is not yet installed.

active directory powershell module

To install, run this command:

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

powershell import active directory module

Wait for the installation to finish.

import active directory module powershell

Using DISM.exe

You can also install RSAT using the DISM.exe tool. To do so, open an elevated CMD or PowerShell and run this command.

DISM.exe /Online /Add-Capability /CapabilityName:Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0

active directory module for windows powershell

Import PowerShell Active Directory Module after Installing

Now that you’ve installed the PowerShell Active Directory Module, you can import it into Windows PowerShell using this command.

Import-Module ActiveDirectory

powershell install active directory module windows 11

If you’re using PowerShell 7+, use the Windows PowerShell compatibility switch (-UseWindowsPowerShell).

powershell import module active directory

Import PowerShell Active Directory Module without Installing

You can also import the PowerShell Active Directory Module from a remote computer that has it. This way, you do not have to install it first.

First, create a session object to the remote command by running this command on your local PowerShell window. This method uses PowerShell remoting via WinRM.

$session = New-PSSession -ComputerName DC1

Next, export the ActiveDirectory module from the remote computer to the local computer. The module is saved to $env:HOMEPATH\Documents\WindowsPowerShell\Modules\<MODULE NAME> folder.

Export-PSsession -Session $session -Module ActiveDirectory -OutputModule RemoteADModule

Now that the ActiveDirectory module is exported as RemoteADModule to your local machine, you can import it like so:

Import-Module RemoteADModule

powershell ad module

Using the Active Directory PowerShell Module

So you’ve installed the Active Directory PowerShell Module. What’s next? Well, it’s up to you. You can now manage the Active Directory using the various cmdlets at your disposal.

Cyril Kardashevsky

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.

How to Install Active Directory Powershell Module and Import. We can use the Remote Server Administration Tools (RSAT) to manage roles and features on Windows Server hosts from our workstations. RSAT contains graphical MMC snap-ins, command-line tools, and PowerShell modules. This article will discuss installing the RSAT package on Windows 10, 11, and Windows Servers 2022, 2019, and 2022 using the Windows GUI and the PowerShell console via Feature on Demand (FoD).

How to Install Active Directory PowerShell Module and Import.

Installing Remote Server Administration Tools

Before we begin, it is crucial to understand the Remote Server Administration Tools (RSAT) package. We must install the RSAT package if we use a Windows machine, workstation, or server. We use the RSAT package to manage Windows operating system machines remotely.

The PowerShell Active Directory Module is one example of a component that requires the RSAT package. We get the thrown error when we run active directory commands without RSAT, as shown in the screenshot below.

Importing the AD Module with no RSAT

As a result, before proceeding, we must first install the prerequisites.

Installing RSAT on Windows 10

We previously installed RSAT as a separate .MSU executable file that had to be downloaded manually from the Microsoft website. We need to install the package after each Windows build upgrade.

Since October 2018, the RSAT package no longer needs to be manually downloaded. The RSAT installation package is now built into the Windows 10 image and installed as a standalone feature (Features on Demand). We can now install RSAT from the Settings app in Windows 10.

Install Active Directory Powershell Module and Import. install rsat windows 10 in optional features

Alternatively, we can also install all of the RSAT package components through PowerShell with the following command below:

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

The command above will install all available RSAT tools inside the machine.

Installing RSAT on Windows 11

Like Windows 10, we can also install RSAT on Windows 11 through the Settings app -> Apps -> Optional Features -> click on Add an optional feature (View features) panel. Select the required RSAT packages and click Install.

install rsat windows 11 in optional features

We can also install RSAT in Windows 11 via PowerShell:

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

Installing RSAT on Windows Server 2016, 2019, and 2022

On Windows Server, we don’t need internet access to install RSAT. Instead, we can install RSAT when the corresponding Windows Server roles or features dependencies are available. Additionally, we can install them via the Server Manager by going to Add Roles and Features -> Features -> click on Remote Server Administration Tools

We can locate all RSAT components in two sections: the Feature Administration Tools and Role Administration Tools. Select the required options and click Next.

Install Active Directory Powershell Module and Import. windows server install remote server administration tools

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

Frequent RSAT Installation Issues

RSAT installations usually run smoothly with no issues, but occasional problems exist. For example, the RSAT package uses Windows Update to install and integrate RSAT into Windows. Therefore, it may need to be fixed if we temporarily disable the Windows Firewall.

If we have downloaded the RSAT package, but it does not appear or will not install correctly, enable Windows Firewall in the services window, install it, and disable it again. If that didn’t work, there might be other causes.

Frequent RSAT Installation Error Codes

We can use the PowerShell script below to fix the installation:

				
					$registryWU = "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU"
$currentWU = Get-ItemProperty -Path $registryWU -Name "UseWUServer" | select -ExpandProperty UseWUServer

Set-ItemProperty -Path $registryWU -Name "UseWUServer" -Value 0

Restart-Service wuauserv

Get-WindowsCapability -Name RSAT* -Online | Add-WindowsCapability –Online
Set-ItemProperty -Path $registryWU -Name "UseWUServer" -Value $currentWU

Restart-Service wuauserv -force
				
			

Additionally, check the following list below for other frequent RSAT installation issues:

  • 0x8024402c and 0x80072f8f – To download RSAT files, Windows cannot connect to the Microsoft Update service. Examine internet connectivity or install components from a local FoD image. Once checked, execute the following command.
				
					Add-WindowsCapability -Online -Name Rsat.ActiveDirectory.Tools~~~~0.0.1.0 -LimitAccess -Source 
				
			

  • 0x800f081f – make sure that the directory path with RSAT components specified as a value in the –Source parameter exists;
  • 0x800f0950 – the error is similar to the above use case 0x800f0954;
  • 0x80070490 – check and repair your Windows image using Deployment Image Servicing and Management (DISM) with the following command below: 
				
					DISM /Online /Cleanup-Image /RestoreHealth
				
			

Improve your Active Directory Security & Azure AD

Try us out for Free, Access to all features. – 200+ AD Report templates Available. Easily customise your own AD reports.

Import the PowerShell Active Directory Module

After installing the module, PowerShell will most likely automatically import it. However, if we want to ensure that it loads correctly, we can use the Import-Module command.

The command below will import the Windows PowerShell Active Directory module. There should be no errors if the installed module is correct.

				
					Import-Module ActiveDirectory
				
			

Connecting and Authenticating with Active Directory

After successfully installing the Active Directory (AD) module, we can use the PowerShell Active Directory module cmdlets. The following section of this article will go over connecting to a specific Domain Controller (DC).

Connecting to an Active Directory Domain Controller

The Active Directory cmdlets will default locate a domain controller for us. However, if we need to authenticate to a different DC, we can use the -Server parameter. As mentioned, most of the AD commands accept the -Server parameter like the following snippet of code below.

				
					Get-ADUser -Filter "Name -eq 'Marion'" -SearchBase "DC=IT" -Server DC01.infrasos.com
				
			

Also, by default, PowerShell will automatically find a DC to connect if we still need to supply the -Server parameter. We determine the primary DC by trying the following:

  1. Use the value provided in the -Server parameter.
  2. Use the current domain controller associated with the AD PowerShell provider.
  3. Use the existing domain of the client’s machine.

By specifying a value for the -Server parameter, we can connect to a particular DC. We can select a variety of Active Directory Domain Services (ADDS) objects in various formats, including:

  • Netbios or Fully Qualified Domain Name (FQDN) of the domain, such as infrasos.com.
  • Netbios or FQDN of the server acting as the domain controller, such as DC01.infrasos.com.
  • An FQDN controller and an open Lightweight Directory Access Port (LDAP) port such as DC01.infrasos.com:3268

Connecting to Active Directory with Different Credentials

By default, the AD PowerShell commands will use two steps for determining the user credentials when connecting to AD.

  1. Use the current credentials associated with the drive if the executed commands are from the PowerShell AD Provider.
  2. Utilizing the credentials of the logged-on user.

We can also specify alternate credentials using the –Credential parameter. The -Credential parameter allows us to pass in a credential object called PSCredential. For example, using an alternate credential, we can see the snippet below of the Windows AD PowerShell Get-ADUser cmdlet.

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

We also have two authentication options. As the default parameter, these types are Basic and Negotiate. Basic authentication is only possible if we encrypt our connection with SSL.

				
					Get-Aduser -Filter * -Credential $credential -AuthType 
				
			

Thank you for reading How to Install Active Directory Powershell Module and Import. We shall conclude.

How to Install Active Directory PowerShell Module and Import Conclusion

Importing the Windows PowerShell ActiveDirectory module is a straightforward and standard process. We must first install the correct RSAT version as a prerequisite. Then, using the comprehensive steps provided in this article, we should be able to install and import the ActiveDirectory module and use Active Directory commands accordingly.

Try InfraSOS for FREE

Invite your team and explore InfraSOS features for free

  • Free 15-Days Trial
  • Easy Setup
  • Full Access to Enterprise Plan

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.

Scan Your AD for 930+ Million Compromised Passwords. Download Specops Password Auditor, a FREE read only tool that identifies password-related vulnerabilities.

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

Are there compromised passwords in your Active Directory? Download Specops Password Auditor and scan for free.

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

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как скрыть приложение в трее windows 10
  • Техподдержка windows server 2016
  • Windows update assistant windows 10 x64
  • Не работают горячие клавиши windows 10 на ноутбуке
  • Avs video editor for windows xp