List users in group windows

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

Ранее для построения списка пользователей в группах Active Directory приходилось использовать скрипты VBScript, или утилиты командной строки DSQuery или CSVDE, недостаточно гибкие и удобные.

Для взаимодействия с AD Microsoft разработала специальный модуль Active Directory Module для Windows PowerShell. Впервые данный модуль появился в Windows Server 2008 R2 и для его использования нужно сначала его загрузить в вашу сессию PowerShell командой:

Import-Module ActiveDirectory

В Windows Server 2012 / R2 / Windows Server 2016 этот модуль автоматически устанавливается и загружается при установке на сервере роли ADDS (Active Directory Domain Services), т.е. при повышении сервера до контроллера домена.

В настольных пользовательских операционных системах (Windows 10 / 8 / 7) модуль Active Directory для Windows PowerShell входит в состав RSAT, который нужно скачать, устанавливать и активировать модуль для работы с AD отдельно.

Модуль Active Directory для Windows PowerShell

Обратите внимание, что для использования в сессии PowerShell модуля ActiveDirectory не обязательно иметь права администратора домена. Получить информацию о пользователях и группах из AD может любой аутентифицированный пользователь домена.

Для получения информации об учетных записях, которые входят в группу безопасности Active Directory используется командлет Get-ADGroupMember.

Например, чтобы вывести на экран список членов группы Domain Admins, нужно выполнить команду:

Get-ADGroupMember 'Domain Admins'

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

Get-ADGroup -filter * | sort name | select Name

Чтобы отобразить только имена пользователей в группе:

Get-ADGroupMember -Identity 'Domain Admins'| ft name

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

Get-ADGroupMember -Identity ‘Domain Admins’ -Recursive | ft name

Переключатель –recursive предписывает команде get-adgroupmember получать список пользователей из каждой вложенной группы и выводить только объекты, не являющиеся контейнерами (пользователей или компьютеры). Т.е. данная команда отобразит даже тех пользователей, которые напрямую не входят в группу.

Можно вывести более подробную информацию об учетных записях в данной группе таким образом:

Get-ADGroupMember -Identity ‘Domain Admins’ | foreach { Get-ADUser $_ -Properties * }

Рассмотрим более сложную конструкцию PowerShell, которая позволяет вывести всех членов определённой доменной группы безопасности с информацией о компании, подразделении и должности с последующей сортировкой и разбивкой на блоки с зависимости от конкретного аттрибута (допустим нам нужно сгруппировать пользователей по полю Компания — company ):

Get-ADGroupMember -Recursive ‘Domain Admins’ | ForEach {Get-ADUser -filter {samaccountname -eq $_.SamAccountName} -Properties displayName, company, title, department} | Sort-Object company,displayName | Format-Table displayName,company,department,title -GroupBy company -AutoSize

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

| Out-File -Width 4000 "C:\TxT\GetUsersADGroupByCompany.txt"

Для выгрузки списка пользователей группы в CSV файл нужно добавить такой конвейер:

| Export-Csv -NoTypeInformation .\GetUsersADGroupByCompany.csv -Encoding Unicode

Можно посчитать общее количество пользователей в группе:

(Get-ADGroupMember -Identity 'Domain Admins').Count

Еще один полезный пример. Попробуем найти все группы AD содержащие в имени шаблон *Manager*, и выведем пользователей, которые входят в эти группы. Чтобы выводить только уникальные объекты, воспользуемся аргументом -uniq.

Get-ADGroup -filter 'SamAccountName -like "*Manager*"' | Get-ADGroupMember -recursive|Select-Object -uniq

Если при выполнении команды Get-ADGroupMember появится ошибка:

Get-ADGroupMember : The specified directory service attribute or value does not exist

Значит в состав группы входят пользователи из других лесов. Командлет Get-ADGroupMember не поддерживает работу с пользователями из разных лесов AD.

Для добавления пользователей в группы AD нужно использовать командлет Add-ADGroupMember.

Solution 1:

Here’s another way from the command prompt, not sure how automatable though since you would have to parse the output:

If group is «global security group»:

net group <your_groupname> /domain

If you are looking for «domain local security group»:

net localgroup <your_groupname> /domain

Solution 2:

Here’s a version of the ds command I found more typically useful, especially if you have a complex OU structure and don’t necessarily know the full distinguished name of the group.

dsquery group -samid "Group_SAM_Account_Name" | dsget group -members -expand

or if you know the CN of the group, usually the same as the SAM ID, quoted in case there are spaces in the name:

dsquery group -name "Group Account Name" | dsget group -members -expand

As stated in the comments, by default the ds* commands (dsquery, dsget, dsadd, dsrm) are only available on a Domain Controller. However, you can install the Admin Tools pack from the Support Tools on the Windows Server installation media or download it from the Microsoft Download site.

You can also perform these queries using PowerShell. PowerShell is already available as an installable feature for Server 2008, 2008 R2, and Windows 7, but you’ll need to download the WinRM Framework to install it on XP or Vista.

To get access to any AD-specific cmdlets in PowerShell you will ALSO need to perform at least one of the following installs:

  • For Win 7 and 2008 R2 clients, you can install the Remote Server Admin Tools. The RSAT also requires that you have installed the Active Directory Web Services feature on your Server 2008 R2 Domain Controllers, or the Active Directory Management Gateway Service for any Server 2003/2008 DCs.
  • For any XP or higher client, download and install the Quest ActiveRoles Management Shell for Active Directory. The Quest tools do not require any additional changes to your DCs.

Solution 3:

try

dsget group "CN=GroupName,DC=domain,DC=name,DC=com" -members

Solution 4:

For a PowerShell solution that doesn’t require the Quest AD add-in, try the following

Import-Module ActiveDirectory

Get-ADGroupMember "Domain Admins" -recursive | Select-Object name

This will enumerate the nested groups as well. If you don’t wish to do so, remove the -recursive switch.


Solution 5:

A very easy way which works on servers and clients:

NET GROUP "YOURGROUPNAME" /DOMAIN | find /I /C "%USERNAME%"

Returns 1 if user is in group YOURGROUPNAME, else will return 0

You can then use the %ERRORLEVEL% value (0 if user in group, 1 if not) like

IF %ERRORLEVEL%==0 NET USE %LOGONSERVER%\YOURGROUPSHARE

The Active Directory Users and Computers (ADUC) graphical MMC snap-in can be used to view the list of Active Directory groups that the user is a member of. Simply open this snap-in (run the dsa.msc command), find the user and go to the Member of tab. This shows the current user’s AD group membership.

However, this method only shows the user’s direct group membership and does not allow you to export a list of groups in any form. To list all the groups that the user is a member of (including nested ones) and export the list to a CSV/TXT file, it is more convenient to use command-line tools or PowerShell cmdlets.

check ad group membership

List AD groups a user is a member of with PowerShell

To check the user’s membership in AD groups, use the cmdlets from the PowerShell Active Directory module. Use one of the following commands:

Get-ADPrincipalGroupMembership jbrion | Select name

or

Get-ADUser jbrion -Properties Memberof | Select -ExpandProperty memberOf

Both commands list the Active Directory groups the jbrion user account is a member of. However, the output doesn’t include nested AD groups.

powershell check ad group membership

To include nested group membership to the output, use the following PowerShell script, which uses a simple LDAP filter to check the membership:

$username = 'jbrion'

$filter = "member:1.2.840.113556.1.4.1941:=" + (Get-ADUser $username).DistinguishedName
Get-ADGroup -LDAPFilter "($filter)" |select SamAccountName,ObjectClass

how to see what ad groups i am in cmd

Export AD Group Members to CSV using PowerShell

To export the resulting AD group membership report to a text or CSV file, you can use the >> operator or the Export-CSV cmdlet.

For example, export the list of Distinguished Names (DNs) of all the groups the user is a member of to a plain TXT file:

Get-ADUser j.brion -Properties Memberof | Select -ExpandProperty memberOf >> c:\ps\ad_group.txt

command to check ad group membership

Or select the group attributes you need and export the group membership to a CSV file:

Get-ADPrincipalGroupMembership j.brion | Select-Object name,description,GroupCategory,GroupScope,distinguishedName| Export-Csv -NoTypeInformation c:\ps\ad_group.csv -Encoding UTF8

check ad group membership powershell

List Active Directory Group Members with PowerShell

In some cases, you may need to view a full list of AD group members (including nested ones). Use this command:

Get-ADGroupMember -Identity fs01-salary -Recursive | ft SamAccountName, SID, name

how to check ad groups in windows

If you need to add specific user attributes for each group member, add the foreach loop:

Get-ADGroupMember -Identity fs01-salary -Recursive | foreach { Get-ADUser $_ -Properties * } | select displayName,company,department,title,email

Check AD Group Membership via Command Line

You can also list the Active Directory user’s group membership from the command prompt using the built-in net user command:

NET USER username /DOMAIN

The command output contains the user’s domain (Global Group Memberships) and Local Group Memberships.

list members of ad group command line

If you need to list all users who are members of a specified AD group from cmd, use the net group command. For example:

NET GROUP "group name" /DOMAIN

If you need to list the security groups that your account is a member of, run:

whoami /groups

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.

Native Solution

Netwrix Auditor for Active Directory

Steps

To see user’s AD group membership using the command line:

  1. Open the command prompt by navigating to Start → Run (or pressing Win + R) and entering «cmd».
  2. Type the following command in the command line, specifying the user account you want to find group membership for:

net user username

  1. At the end of the resulting report, you will find a list of the local groups and global groups that the user belongs to:

To list members of AD group using the command line:

  1. Open the command prompt by navigating to Start → Run (or pressing Win + R) and entering «cmd».
  2. Enter the following command, specifying the required group name:

net localgroup groupname

  1. At the end of the resulting report, you will find a list of the members of the group:

NET commands also work if you need to check local users and group membership in Windows 10.

To see which groups a particular user belongs to:

  1. Run Netwrix Auditor → Navigate to «Reports» → Click “Predefined” → Expand the «Active Directory» section → Go to «Active Directory — State-in-Time» → Select «User Accounts — Group Membership»→ Click “View.»
  2. Specify “Enabled” in the “Status” field and type “user” in the “Member Type” field -> Click “View Report.”

To check AD group members:

  1. Run Netwrix Auditor → Navigate to “Reports” → Click “Predefined” → Expand the “Active Directory” section → Go to “Active Directory – State-in-Time” → Select “Group Members” → Click “View”.
  2. Set up the following filters:
  • Status: Enabled
  • Member Type: User
  • Group path: The group path. You can specify the partial path to a particular group, using % as the wildcard character, or leave the wildcard to see a report for all groups.
  1. Click “View Report”.

Grasp the Full Picture Instead of Tinkering with the Command Line

Best practices advise using Active Directory groups to grant access privileges to users — for example, access to specific computers, tools, and servers. However, over time, AD group configuration can get very complicated, making it challenging to understand who has access to what and ensure each user only has the permissions they need. IT admins often need to check AD group members in Windows 10 or detail all the groups that a particular user belongs to and then either provide that information to departmental leaders for access privilege attestation or analyze it themselves to fix broken inheritance and other security issues.

You can view AD group membership with the Active Directory Users and Computers (ADUC) console snap-in by finding the user or group of interest, drilling down into the object’s properties, and clicking the “Members” or “Member Of” tab. Another option is to get group membership with the command line — you can use the dsget user and dsquery group tools from the Active Directory Domain Services (AD DS) package, or native NET commands from the command line. However, the results of the NET USER and NET LOCALGROUP commands are hard to parse. While dsget and dsquery can be used to query ad group membership and provide more structured output, those commands work only on server versions of Windows and require you to input the distinguished name in LDAP Data Interchange Format. The last option is to use the Get-ADGroupMemberPowerShell cmdlet, which requires some scripting skills. As a result, reviewing Active Directory group membership with native tools can be difficult and time-consuming. 

Netwrix Auditor for Active Directory can save a great deal of precious time. Instead of checking AD group membership with a command line, system operators can get a group membership summary in a few clicks. In addition, Netwrix Auditor also reports on modifications, logon activity, and the configuration of Active Directory and Group Policy, including inactive user and computer accounts, Active Directory object permissions, and more. It will alert you to possible threats and offers an advanced search to speed investigations. You can use various predefined reports, all with filtering, exporting, and subscription options, and easily create your custom reports. This comprehensive functionality streamlines many everyday IT tasks, from change monitoring and access control to privilege review and anomalous behavior detection.

Обновлено:
Опубликовано:

Тематические термины: Active Directory, Powershell

Чтение информации
    Список всех групп в AD DS
    Подробная информация о группе
    Члены группы
    Сколько пользователей в группе
    В каких группах состоит пользователь
    Поиск пустых групп
    Кто не входит в конкретную группу
Действия над группами
    Добавление в группу
    Создание группы
    Удаление пользователя из группы

Получение информации

1. Список всех групп

Без фильтра:

Get-AdGroup -filter *

С фильтром:

Get-AdGroup -filter * | Where {$_.name -like «*free*»} | fl name

* будут выбраны все группы, в названии которых встречается free.

2. Подробная информация о группе

Get-ADGroup «Domain Users» -Properties *

* где ключ -Properties * покажет информацию о всех атрибутах группы.

Показать только SID и GUID группы:

Get-ADGroup «Domain Admins» | ft ObjectGUID, SID

3. Посмотреть членов группы

Перечень членов групп с базовой информацией о каждом пользователе:

Get-ADGroupMember -Identity Administrators

Вывести на экран только имена пользователей:

Get-ADGroupMember -Identity Administrators | ft name

Рекурсивный запрос:

Get-ADGroupMember -Identity Administrators -Recursive | ft name

* в данном примере используется ключ Recursive — это позволяет вывести на экран не только членов группы Administrators, но и членов групп, которые входят в эту группу.

Вывести членов групп с подробной информацией по каждому из них:

Get-ADGroupMember -Identity «Users» | foreach { Get-ADUser $_ -Properties * }

4. Количество пользователей в группе

Расчет выполняется методом Count:

(Get-ADGroupMember -Identity Administrators).Count

5. В каких группах состоит пользователь

Задача немного обратная — работаем с пользователем и отображаем список групп, в которые он входит:

Get-ADUser Administrator -Properties Memberof | Select -ExpandProperty memberOf

6. Список пустых групп

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

Get-ADGroup -filter * | where {-Not ($_ | Get-ADGroupMember)} | Select Name

7. Cписок пользователей, которые не входят в конкретную группу

Get-ADuser -Filter * -Properties MemberOf | where { -Not ($_.MemberOf -match «Managers») } | Select Name

* в данном примере мы увидем список пользователей, которые не входят в группу Managers.

Действия с группами AD

1. Добавить пользователя в группу

Add-ADGroupMember «Domain Admins» dmosk

* в данном примере пользователь dmosk будет добавлен в группу Domain Admins.

2. Создать новую группу

New-ADGroup -GroupScope DomainLocal -Path «OU=Группы,DC=dmosk,DC=local» -Name «Отдел строительства космических кораблей»

* где GroupScope DomainLocal задает локальную область действия; Path определяет размещение группы в дереве Active Directory.

3. Удалить пользователя из группы

Remove-ADGroupMember -Confirm:$false -Identity «Domain Users» -Members dmosk

* удаляем пользователя dmosk из группы Domain Users. Ключ -Confirm:$false используется для автоматического подтверждения действия (система не станет запрашивать, точно ли Вы хотите удалить пользователя из группы).

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

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Ошибка fortnite windows 10
  • Curl не является внутренней или внешней командой windows 10
  • Гаджет новостей windows 7
  • Стики нотес windows 10
  • Windows defender exploit guard что это