Powershell search-adaccount cmdlet with examples

Description

The Enable-ADAccount cmdlet enables an Active Directory user, computer, or service account.

The Identity parameter specifies the Active Directory user, computer, or service account that you want to enable.
You can identify an account by its distinguished name, GUID, security identifier (SID) or Security Accounts Manager (SAM) account name.
You can also set the Identity parameter to an object variable such as , or you can pass an account object through the pipeline to the Identity parameter.
For example, you can use the Get-ADUser cmdlet to retrieve an account object and then pass the object through the pipeline to the Enable-ADAccount cmdlet.
Similarly, you can use Get-ADComputer and Search-ADAccount to retrieve account objects.

Ответы 2

Решение с Get-ADUser

Вы по-прежнему можете использовать для поиска учетных записей, если используете правильный фильтр:

Это даст вам каждую учетную запись, для которой не задано значение атрибута .

Решение с помощью Search-ADAccount

Если вы все еще хотите использовать , вы должны указать временную метку до истечения срока действия учетных записей (взгляните на реф.). Нет возможности искать учетные записи, для которых не установлено какое-либо значение. Вы всегда должны предлагать какой-то DateTime.

Например, если вы хотите найти все учетные записи, срок действия которых истекает через 2 недели, у вас есть следующие варианты:

Первый:

Решение с датой истечения срока действия учетной записи:

Второй:

Решение на оставшиеся дни до истечения срока действия аккаунта:

Комментарии (1)

Я нашел решение, сочетающее ответ Paxz выше и этот Тема Технета. «AccountExpirationDate» слишком сложно эффективно отфильтровать из AD без экспорта даты истечения срока действия учетной записи каждого пользователя и форматирования ее в удобочитаемую строку даты и времени.

В приведенной выше статье Technet объясняется, что «Атрибут accountExpires AD представляет собой большое целое (64-разрядное), представляющее даты (в формате UTC) в виде количества 100-наносекундных интервалов с 00:00 1 января 1601 года. Параметр AccountExpirationDate — это метод свойства, который преобразует значение accountExpires в соответствующая дата в местном часовом поясе». Согласно дополнительным исследованиям, когда для учетной записи установлено значение «Никогда не истекает», она будет иметь целое число «accountexpires», равное 9223372036854775807.

«Get-ADUser» можно использовать для фильтрации всех учетных записей, где целое число «accountexpires» равно «9223372036854775807». Это позволяет избежать необходимости конвертировать дату для каждой учетной записи в домене.

Description

The Set-ADAccountPassword cmdlet sets the password for a user, computer, or service account.

The Identity parameter specifies the Active Directory account to modify.

You can identify an account by its distinguished name, GUID, security identifier (SID) or security accounts manager (SAM) account name.
You can also set the Identity parameter to an object variable such as , or you can pass an object through the pipeline to the Identity parameter.
For example, you can use the Search-ADAccount cmdlet to retrieve an account object and then pass the object through the pipeline to the Set-ADAccountPassword cmdlet.
Similarly, you can use Get-ADUser, Get-ADComputer, or Get-ADServiceAccount, for standalone MSAs, cmdlets to retrieve account objects that you can pass through the pipeline to this cmdlet.

Note: Group MSAs cannot set password since they are changed at predetermined intervals.

For Active Directory Lightweight Directory Services (AD LDS) environments, the Partition parameter must be specified except in the following two conditions:

  • The cmdlet is run from an Active Directory provider drive.
  • A default naming context or partition is defined for the AD LDS environment.

To specify a default naming context for an AD LDS environment, set the msDS-defaultNamingContext property of the Active Directory directory service agent (DSA) object (nTDSDSA) for the AD LDS instance.

Description

The Enable-ADAccount cmdlet enables an Active Directory user, computer, or service account.

The Identity parameter specifies the Active Directory user, computer, or service account that you want to enable.
You can identify an account by its distinguished name, GUID, security identifier (SID) or Security Accounts Manager (SAM) account name.
You can also set the Identity parameter to an object variable such as , or you can pass an account object through the pipeline to the Identity parameter.
For example, you can use the Get-ADUser cmdlet to retrieve an account object and then pass the object through the pipeline to the Enable-ADAccount cmdlet.
Similarly, you can use Get-ADComputer and Search-ADAccount to retrieve account objects.

Description

The Enable-ADAccount cmdlet enables an Active Directory user, computer, or service account.

The Identity parameter specifies the Active Directory user, computer, or service account that you want to enable.
You can identify an account by its distinguished name, GUID, security identifier (SID) or Security Accounts Manager (SAM) account name.
You can also set the Identity parameter to an object variable such as , or you can pass an account object through the pipeline to the Identity parameter.
For example, you can use the Get-ADUser cmdlet to retrieve an account object and then pass the object through the pipeline to the Enable-ADAccount cmdlet.
Similarly, you can use Get-ADComputer and Search-ADAccount to retrieve account objects.

Description

The Unlock-ADAccount cmdlet restores Active Directory Domain Services (AD DS) access for an account that is locked.
AD DS access is suspended or locked for an account when the number of incorrect password entries exceeds the maximum number allowed by the account password policy.

the Identity parameter specifies the Active Directory account to unlock.
You can identify an account by its distinguished name, GUID, security identifier (SID) or Security Accounts Manager (SAM) account name.
You can also set the Identity parameter to an account object variable such as , or you can pass an object through the pipeline to the Identity parameter.
For example, you can use the Search-ADAccount cmdlet to get an account object and then pass the object through the pipeline to the Unlock-ADAccount cmdlet to unlock the account.
Similarly, you can use Get-ADUser and Get-ADComputer to get objects to pass through the pipeline.

For Active Directory Lightweight Directory Services (AD LDS) environments, the Partition parameter must be specified except when:

  • Using a distinguished name to identify objects: the partition is auto-generated from the distinguished name.
  • Running cmdlets from an Active Directory provider drive: the current path is used to set the partition.
  • A default naming context or partition is specified.

To specify a default naming context for an AD LDS environment, set the msDS-defaultNamingContext property of the Active Directory directory service agent object (nTDSDSA) for the AD LDS instance.

Description

The Disable-ADAccount cmdlet disables an Active Directory user, computer, or service account.

The Identity parameter specifies the Active Directory user, computer service account, or other service account that you want to disable.
You can identify an account by its distinguished name, GUID, security identifier (SID), or Security Accounts Manager (SAM) account name.
You can also set the Identity parameter to an object variable such as , or you can pass an account object through the pipeline to the Identity parameter.
For example, you can use the Get-ADUser cmdlet to retrieve a user account object and then pass the object through the pipeline to the Disable-ADAccount cmdlet.
Similarly, you can use Get-ADComputer and Search-ADAccount to retrieve account objects.

For Active Directory Lightweight Directory Services (AD LDS) environments, the Partition parameter must be specified except in the following two conditions:

  • The cmdlet is run from an Active Directory provider drive.
  • A default naming context or partition is defined for the AD LDS environment.
    To specify a default naming context for an AD LDS environment, set the msDS-defaultNamingContext property of the Active Directory directory service agent (DSA) object (nTDSDSA) for the AD LDS instance.

Description

The Unlock-ADAccount cmdlet restores Active Directory Domain Services (AD DS) access for an account that is locked.
AD DS access is suspended or locked for an account when the number of incorrect password entries exceeds the maximum number allowed by the account password policy.

the Identity parameter specifies the Active Directory account to unlock.
You can identify an account by its distinguished name, GUID, security identifier (SID) or Security Accounts Manager (SAM) account name.
You can also set the Identity parameter to an account object variable such as , or you can pass an object through the pipeline to the Identity parameter.
For example, you can use the Search-ADAccount cmdlet to get an account object and then pass the object through the pipeline to the Unlock-ADAccount cmdlet to unlock the account.
Similarly, you can use Get-ADUser and Get-ADComputer to get objects to pass through the pipeline.

For Active Directory Lightweight Directory Services (AD LDS) environments, the Partition parameter must be specified except when:

  • Using a distinguished name to identify objects: the partition is auto-generated from the distinguished name.
  • Running cmdlets from an Active Directory provider drive: the current path is used to set the partition.
  • A default naming context or partition is specified.

To specify a default naming context for an AD LDS environment, set the msDS-defaultNamingContext property of the Active Directory directory service agent object (nTDSDSA) for the AD LDS instance.

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

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

$fqdn = Get-ADDomain
$fulldomain = $fqdn.DNSRoot
$domain = $fulldomain.split(".")
$Dom = $domain
$Ext = $domain
$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 появляется следующая структура подразделений.

Контекст & рекомендации

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

У учетных записей пользователей есть атрибут под названием PasswordLastSet, куда записывается последний раз, когда пользователь изменил свой пароль. Поскольку PasswordLastSet является реплицированным атрибутом, необходимо опрашивать лишь один контроллер домена в каждом домене.

Windows Server 2003 представила новый атрибут под названием lastLogonTimeStamp, чтобы помочь в выявлении потенциально устаревших учетных записей. Этот атрибут активируется в домене, установленном на режим работы Windows Server 2003, Windows Server 2008, Windows Server 2008R2, Windows Server 2012 или Windows Server 2012R2. В отличие от атрибута lastLogon, который был доступен с Windows NT 4.0, lastLogonTimeStamp реплицируется при каждом своем обновлении. Запрос этого атрибута более удобен, так как необходимо опрашивать только один контроллер домена в каждом домене.

Чтобы найти нужные учетные записи, запустите скрипт, опрашивающий Active Directory на предмет наличия неактивных учетных записей пользователей. В модуле Active Directory для Windows PowerShell команда Search-ADAccount -AccountInactive -UsersOnly возвращает все неактивные учетные записи пользователей. Используйте переключатели -DateTime или -TimeSpan, чтобы сузить дату, когда был произведен последний вход.

Примечание. Атрибут Lastlogontimestamp не реплицируется каждый раз, когда кто-то входит в систему. См. Общие сведения об атрибутах учетной записи AD — LastLogon, LastLogonTimeStamp и LastLogonDate по адресу https://social.technet.microsoft.com/wiki/contents/articles/22461.understanding-the-ad-account-attributes-lastlogon-lastlogontimestamp-and-lastlogondate.aspx.

Работа с устаревшими учетными записями пользователей часто сводится к внедрению эффективных процессов отзыва данных. Однако не исключено, что пользователи по тем или иным причинам могут оказаться неспособны работать и, следовательно, входить в систему в течение длительного периода времени. Учетные записи служб также могут не входить в систему в течение длительного времени. Поэтому следует включить несколько проверок и предусмотреть меры, предотвращающие отключение или удаление учетных записей, которые все еще используются.

Как с помощью PowerShell найти компьютер на котором была заблокирована учётная запись

Вы можете использовать следующий скрипт PowerShell, чтобы найти источник блокировки учётной записи конкретного пользователя в журналах событий PDC. Этот скрипт возвращает время блокировки и имя компьютера, с которого она произошла (замените Alex на имя интересующего вас пользователя):

$Usr = 'Alex'
$Pdc = (Get-AdDomain).PDCEmulator
$ParamsEvn = @{
	'Computername' = $Pdc
	'LogName' = 'Security'
	'FilterXPath' = "* and EventData='$Usr']]"
}
$Evnts = Get-WinEvent @ParamsEvn 
$Evnts | ForEach-Object {$_.Properties.value + ' ' + $_.TimeCreated + ', UserName: ' + $Usr}

Пример полученных данных:

HACKWARE-WIN 09/29/2021 07:31:59
HACKWARE-WIN 09/29/2021 06:53:12
HACKWARE-WIN 09/29/2021 05:44:18

Если вы хотите ограничить вывод журнала, например, только последними двумя днями, то используйте следующий скрипт:

$Usr = 'Alex'
$Date = (Get-Date).AddDays(-2)
$Evnts = Get-WinEvent -FilterHashtable @{ LogName='Security'; StartTime=$Date; Id='4740'; Data="$Usr";  }
$Evnts | ForEach-Object {$_.Properties.value + ' ' + $_.TimeCreated + ', UserName: ' + $_.Properties.value}

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

$Usr = 'MiAl'
Get-ADDomainController -Filter * | Select-Object -exp hostname | % {
	$ParamsEvn = @{
		'Computername' = $Pdc
		'LogName' = 'Security'
		'FilterXPath' = "* and EventData='$Usr']]"
	}
	$Evnts = Get-WinEvent @ParamsEvn
	$Evnts | ForEach-Object {$_.MachineName + " " + $_.Properties.value + ' ' + $_.TimeCreated + ', UserName: ' + $_.Properties.value}
}

Description

The Unlock-ADAccount cmdlet restores Active Directory Domain Services (AD DS) access for an account that is locked.
AD DS access is suspended or locked for an account when the number of incorrect password entries exceeds the maximum number allowed by the account password policy.

the Identity parameter specifies the Active Directory account to unlock.
You can identify an account by its distinguished name, GUID, security identifier (SID) or Security Accounts Manager (SAM) account name.
You can also set the Identity parameter to an account object variable such as , or you can pass an object through the pipeline to the Identity parameter.
For example, you can use the Search-ADAccount cmdlet to get an account object and then pass the object through the pipeline to the Unlock-ADAccount cmdlet to unlock the account.
Similarly, you can use Get-ADUser and Get-ADComputer to get objects to pass through the pipeline.

For Active Directory Lightweight Directory Services (AD LDS) environments, the Partition parameter must be specified except when:

  • Using a distinguished name to identify objects: the partition is auto-generated from the distinguished name.
  • Running cmdlets from an Active Directory provider drive: the current path is used to set the partition.
  • A default naming context or partition is specified.

To specify a default naming context for an AD LDS environment, set the msDS-defaultNamingContext property of the Active Directory directory service agent object (nTDSDSA) for the AD LDS instance.

Description

The Unlock-ADAccount cmdlet restores Active Directory Domain Services (AD DS) access for an account that is locked.
AD DS access is suspended or locked for an account when the number of incorrect password entries exceeds the maximum number allowed by the account password policy.

the Identity parameter specifies the Active Directory account to unlock.
You can identify an account by its distinguished name, GUID, security identifier (SID) or Security Accounts Manager (SAM) account name.
You can also set the Identity parameter to an account object variable such as , or you can pass an object through the pipeline to the Identity parameter.
For example, you can use the Search-ADAccount cmdlet to get an account object and then pass the object through the pipeline to the Unlock-ADAccount cmdlet to unlock the account.
Similarly, you can use Get-ADUser and Get-ADComputer to get objects to pass through the pipeline.

For Active Directory Lightweight Directory Services (AD LDS) environments, the Partition parameter must be specified except when:

  • Using a distinguished name to identify objects: the partition is auto-generated from the distinguished name.
  • Running cmdlets from an Active Directory provider drive: the current path is used to set the partition.
  • A default naming context or partition is specified.

To specify a default naming context for an AD LDS environment, set the msDS-defaultNamingContext property of the Active Directory directory service agent object (nTDSDSA) for the AD LDS instance.

Description

The Disable-ADAccount cmdlet disables an Active Directory user, computer, or service account.

The Identity parameter specifies the Active Directory user, computer service account, or other service account that you want to disable.
You can identify an account by its distinguished name, GUID, security identifier (SID), or Security Accounts Manager (SAM) account name.
You can also set the Identity parameter to an object variable such as , or you can pass an account object through the pipeline to the Identity parameter.
For example, you can use the Get-ADUser cmdlet to retrieve a user account object and then pass the object through the pipeline to the Disable-ADAccount cmdlet.
Similarly, you can use Get-ADComputer and Search-ADAccount to retrieve account objects.

For Active Directory Lightweight Directory Services (AD LDS) environments, the Partition parameter must be specified except in the following two conditions:

  • The cmdlet is run from an Active Directory provider drive.
  • A default naming context or partition is defined for the AD LDS environment.
    To specify a default naming context for an AD LDS environment, set the msDS-defaultNamingContext property of the Active Directory directory service agent (DSA) object (nTDSDSA) for the AD LDS instance.

Политики аудита входа в систему для контроллеров домена

Чтобы включить фиксацию события блокировки учётной записи в журналах контроллера домена, необходимо активировать следующие политики аудита для контроллеров домена. Перейдите в раздел GPO Computer Configuration → Policies → Windows Settings → Security Settings → Advanced Audit Policy → Logon/Logoff и включите следующие политики:

  • Audit Account Lockout
  • Audit Logon
  • Audit Logoff

В русскоязычной версии это соответственно Конфигурация компьютера → Политики → Конфигурация Windows → Параметры безопасности → Конфигурация расширенной политики аудита → Политика аудита → Вход/Выход, политики:

  • Аудит блокировки учетной записи
  • Аудит входа в систему
  • Аудит выхода из системы

Самый простой способ включить эту политику — через консоль gpmc.msc, отредактировав Default Domain Controller Policy или используя Default Domain Policy на уровне всего домена.

Обратите внимание, что для использования параметров «Конфигурация расширенной политики аудита» также необходимо в Локальной политике безопасности (secpol.msc) включить по пути Параметры безопасности → Локальные политики → Параметры безопасности параметр «Аудит: принудительно переопределяет параметры категории политики аудита параметрами подкатегории политики аудита (Windows Vista или следующие версии)». Это значение по умолчанию установлено на «Включён», поэтому если вы не отключали эту политику, то вам не нужно о ней беспокоиться.

Description

The Enable-ADAccount cmdlet enables an Active Directory user, computer, or service account.

The Identity parameter specifies the Active Directory user, computer, or service account that you want to enable.
You can identify an account by its distinguished name, GUID, security identifier (SID) or Security Accounts Manager (SAM) account name.
You can also set the Identity parameter to an object variable such as , or you can pass an account object through the pipeline to the Identity parameter.
For example, you can use the Get-ADUser cmdlet to retrieve an account object and then pass the object through the pipeline to the Enable-ADAccount cmdlet.
Similarly, you can use Get-ADComputer and Search-ADAccount to retrieve account objects.

Разница между отключённой, просроченной и заблокированной учётной записью

Данная статья посвящена заблокированным аккаунтом (в английской версии это locked out). Но кроме блокировки аккаунта, возможны следующие причины, почему пользователь не может войти в домен:

  • аккаунт отключён
  • аккаунт просрочен
  • пользователь ограничен определённым временем или компьютером для входа

Отключённые аккаунты (disabled)

Администратор домена может вручную отключить (деактивировать) аккаунт пользователя. Если пользователь отключён, то будет выведено сообщение:

Ваша учётная запись отключена. Обратитесь к системному администратору.

Включение аккаунта выполняется администратором (вручную или через скрипт), но не может быть выполнено автоматически, например, по истечении определённого срока действия.

Заблокированные аккаунты (locked out)

Учётная запись может быть заблокирована автоматически в соответствии с политикой блокировки учётной записи организации. Если пользователь ввёл неправильный пароль более определённого количества раз (порог устанавливается политикой паролей), то его аккаунт автоматически блокируется на время, которое также устанавливается политикой паролей.

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

Учётная запись заблокирована и не может использоваться для входа в сеть.

Блокировка может быть снята автоматически после истечения сроки блокировки, установленной в политике паролей домена. Также администратор может ускорить этот процесс и снять блокировку вручную.

Если время разблокировки в групповой политике пароля установлено на 0, то такая учётная запись никогда не будет разблокирована автоматически, для её разблокировки требуется действие администратора домена.

Учётные записи с истекшим сроком действия (expired)

Учётная запись пользователя может быть бессрочной или действующий в течение определённого времени. Удобно установить срок действия учётной записи для временных пользователей, которые должны иметь доступ в домен, например, на период действия контракта с ними. При установки срока истечения действия, системный администратор не пропустит момент когда нужно отключить пользователя.

Запрет доступа по другим причинам

Пользователю может быть разрешено входить только на определённые компьютеры и/или только в определённые часы. Пример сообщения, когда пользователю не разрешено выполнить вход на этом компьютере:

Вы не можете пользоваться этим компьютером из-за ограничений вашей учётной записи. Попробуйте воспользоваться другим компьютером.

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

Вы не можете сейчас войти в систему из-за ограничений вашей учётной записи. Попробуйте ещё раз позже.

Данные ограничения могут перестать действовать в определённые часы или на определённых компьютерах. Эти ограничения устанавливает и снимает администратор домена.

Search-ADAccount and supported parameters

Search-ADAccount supports several parameters to collect the required details. Traditionally, you had to design a script that will connect to an Active Directory context and then search the required details by checking various Active Directory attributes. By using the predefined parameters with the Search-ADAccount PowerShell cmdlet, it is easy as pie for Active Directory administrators to collect the required details. The parameters that are supported with Search-ADAccount cmdlet are listed in the table below:

Parameter Description
-AccountExpiring -AccountExpiring parameter can be used to return accounts that are expiring in the Active Directory. You need to provide value for TimeSpan parameter in the command.
-AccountExpired -AccountExpired parameter can be used if you wish to retrieve accounts that have been expired in the Active Directory domain.
-AccountDisabled As the name suggests, use –AccountDisabled parameter if you need to retrieve the list of accounts that are disabled in the Active Directory domain. –AccountDisabled supports two switches; ComputersOnly and UsersOnly. If you wish to retrieve a list of disabled computer accounts, you will use “-ComputersOnly” and to retrieve only disabled user accounts, use “-UsersOnly”.
-AccountInactive -AccountInactive is used in case you need to retrieve accounts that are inactive in the Active Directory. All you need to do is specify the time span value.
-LockedOut You would want to use –LockedOut parameter if you needed to get a list of accounts that have been locked out.
-PasswordExpired -PasswordExpired parameter can be used if you need to retrieve a list of user accounts whose password have expired.
-PasswordNeverExpires As per the standard security practices, all organization users are required to change their password according to the password policies configured in the Active Directory. In case you need to retrieve a list of user accounts whose password never expires, you will use –PasswordNeverExpires parameter. Usually, service accounts and user accounts which are used by the applications are set to never expire.

Let’s move on to a few examples that use predefined parameters with Search-ADAccount.

Description

The Unlock-ADAccount cmdlet restores Active Directory Domain Services (AD DS) access for an account that is locked.
AD DS access is suspended or locked for an account when the number of incorrect password entries exceeds the maximum number allowed by the account password policy.

the Identity parameter specifies the Active Directory account to unlock.
You can identify an account by its distinguished name, GUID, security identifier (SID) or Security Accounts Manager (SAM) account name.
You can also set the Identity parameter to an account object variable such as , or you can pass an object through the pipeline to the Identity parameter.
For example, you can use the Search-ADAccount cmdlet to get an account object and then pass the object through the pipeline to the Unlock-ADAccount cmdlet to unlock the account.
Similarly, you can use Get-ADUser and Get-ADComputer to get objects to pass through the pipeline.

For Active Directory Lightweight Directory Services (AD LDS) environments, the Partition parameter must be specified except when:

  • Using a distinguished name to identify objects: the partition is auto-generated from the distinguished name.
  • Running cmdlets from an Active Directory provider drive: the current path is used to set the partition.
  • A default naming context or partition is specified.

To specify a default naming context for an AD LDS environment, set the msDS-defaultNamingContext property of the Active Directory directory service agent object (nTDSDSA) for the AD LDS instance.

Description

The Enable-ADAccount cmdlet enables an Active Directory user, computer, or service account.

The Identity parameter specifies the Active Directory user, computer, or service account that you want to enable.
You can identify an account by its distinguished name, GUID, security identifier (SID) or Security Accounts Manager (SAM) account name.
You can also set the Identity parameter to an object variable such as , or you can pass an account object through the pipeline to the Identity parameter.
For example, you can use the Get-ADUser cmdlet to retrieve an account object and then pass the object through the pipeline to the Enable-ADAccount cmdlet.
Similarly, you can use Get-ADComputer and Search-ADAccount to retrieve account objects.

Установка модуля 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 уже активирован и дополнительных действий предпринимать не нужно.

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

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

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

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

Collecting accounts expiring details

When creating user accounts in Active Directory, you can set an expiry date for these accounts. Once the date has expired, the user can no longer log on to a PC that is joined to the Active Directory domain. Generally, the account expiry setting is used for contractors and third-party accounts. In case you wish to get a list of user accounts that are about to expire, you can execute the PowerShell cmdlet below:

As you can see in the above command, Search-ADAccount collects all user accounts that will expire in 10 days. All you need to do is specify a value for the “-TimeSpan” parameter. The output is stored in the C:\TempAccountExpiry.CSV file.

Рейтинг
( Пока оценок нет )
Editor
Editor/ автор статьи

Давно интересуюсь темой. Мне нравится писать о том, в чём разбираюсь.

Понравилась статья? Поделиться с друзьями:
Работатека
Добавить комментарий

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: