Snippet Name: Identify_Nested_AD_Groups
Tags:
Created Date: 2025-06-16 13:12:48
Last Modified Date: 2025-05-31 10:31:40
Dependencies:
DBA Notes:
Sample Output:
Title: Identify Nested AD Groups
Author: user
in Powershell, i need to query a collection of Windows groups to identify any nested windows groups. these groups may or may not have nested groups. ('CIGFINANCIAL\Dev','CIGFINANCIAL\NLS_User','CIGFINANCIAL\ReportAdmin','CIGFINANCIAL\Risk-Analyst','CIGFINANCIAL\ServicingAccounts','CIGFINANCIAL\SQLServerAgent','CIGFINANCIAL\AUTONATIONSQL','CIGFINANCIAL\SQLDBA','CIGFINANCIAL\AppOwnersForSQL','CIGFINANCIAL\AppUsersForSQL','CIGFINANCIAL\AN_DevOps','CIGFINANCIAL\reportdev')
Author: ChatGPT
To query a collection of Windows groups in PowerShell and identify any nested groups, you can use the `Get-ADGroup` cmdlet along with `Get-ADGroupMember` from the Active Directory module. If you don't have the Active Directory module installed, you can do so via the RSAT tools or by installing the module directly if you're on Windows 10 or later.
Here's a script that will iterate through your provided list of groups, check for nested groups, and output the nested groups found:
```powershell
# Ensure the Active Directory module is imported
Import-Module ActiveDirectory
# Define the list of groups
$groups = @(
'CIGFINANCIAL\Dev',
'CIGFINANCIAL\NLS_User',
'CIGFINANCIAL\ReportAdmin',
'CIGFINANCIAL\Risk-Analyst',
'CIGFINANCIAL\ServicingAccounts',
'CIGFINANCIAL\SQLServerAgent',
'CIGFINANCIAL\AUTONATIONSQL',
'CIGFINANCIAL\SQLDBA',
'CIGFINANCIAL\AppOwnersForSQL',
'CIGFINANCIAL\AppUsersForSQL',
'CIGFINANCIAL\AN_DevOps',
'CIGFINANCIAL\reportdev'
)
# Function to find nested groups
function Get-NestedGroups {
param (
[string]$GroupName
)
# Get the group's members
$members = Get-ADGroupMember -Identity $GroupName -Recursive
# Filter the members to only groups
$nestedGroups = $members | Where-Object { $_.objectClass -eq 'group' }
return $nestedGroups
}
# Iterate over each group and check for nested groups
foreach ($group in $groups) {
Write-Host "Checking group: $group"
$nestedGroups = Get-NestedGroups -GroupName $group
if ($nestedGroups.Count -gt 0) {
Write-Host "Nested groups found in $group:"
$nestedGroups | ForEach-Object { Write-Host " - $_.Name" }
} else {
Write-Host "No nested groups found in $group."
}
Write-Host ""
}
```
### Explanation:
1. **Import-Module ActiveDirectory**: Ensures that the Active Directory module is loaded.
2. **$groups**: An array of your specified group names.
3. **Get-NestedGroups Function**: This function takes a group name as a parameter, gets its members recursively, filters out the members to only include those that are groups (i.e., nested groups), and returns these nested groups.
4. **foreach Loop**: Iterates over each group in the `$groups` array, calls the `Get-NestedGroups` function to check for nested groups, and outputs the results.
This script will help you identify nested groups within the specified list of Windows groups.