Любой системный администратор 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
Или через панель Settings -> Apps -> Optional features -> Add a feature -> RSAT: Active Directory Domain Services and Lightweight Directory Services 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
Теперь вы можете использовать командлеты 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
Для установки модуля через панель управления 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 с помощью модуля 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
Вы можете вывести полный список доступных командлетов с помощью команды:
Get-Command –module activedirectory
Общее количество команд в модуле:
Get-Command –module activedirectory |measure-object
Большинство командлетов модуля 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
Примеры использования командлетов Active Directory можно вывести так:
(get-help Set-ADUser).examples
В 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
В этой статье мы рассмотрели, как установить и использовать модулья AD PowerShell для администрирования домена. Надеюсь, эта статья подтолкнет вас к дальнейшему исследованию возможностей этого модуля и автоматизации большинства задач управления AD.
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.
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:
- Use the
Serverproperty of objects passed in on the pipeline. - Use the server associated with the AD PowerShell provider drive, if in use.
- 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.
- Use the credentials associated with the PowerShell AD provider drive, if the command is run from there.
- 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
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
Or through via the Settings -> Apps -> Optional features -> Add a feature -> RSAT: Active Directory Domain Services and Lightweight Directory Services Tools.
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
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
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.
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
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
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:\Windows\System32\WindowsPowerShell\v1.0\Modules - File
ActiveDirectory.Management.dll - File
ActiveDirectory.Management.resources.dll
Then you need to import the module into your current session:
Import-Module C:\PS\ADmodule\Microsoft.ActiveDirectory.Management.dll
Import-Module C:\PS\ADmodule\Microsoft.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 "[email protected]" -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:\ps\export_ad_users.csv
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.
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
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.
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.
On the Dashboard, click “Add roles and features.”
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.
On the Confirmation page, review the selection and click Install.
Wait for the installation to finish and click Close.
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.
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.
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.
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
Click the “View features” button.
In the “Add an optional feature” window, search RSAT, check the “RSAT: Active Directory Domain Services Tools” box, and click Next.
Click Install on the next page.
Wait for the feature to finish installing.
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.
To install, run this command:
Add-WindowsCapability -Online -Name Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0
Wait for the installation to finish.
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
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
If you’re using PowerShell 7+, use the Windows PowerShell compatibility switch (-UseWindowsPowerShell).
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
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).
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.
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.
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.
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-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:
- Use the value provided in the -Server parameter.
- Use the current domain controller associated with the AD PowerShell provider.
- 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.
- Use the current credentials associated with the drive if the executed commands are from the PowerShell AD Provider.
- 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
