Skip to content

Instantly share code, notes, and snippets.

@joshfinley
Created September 25, 2023 16:53
Show Gist options
  • Save joshfinley/d98de9be833e2a07befb64e5ae0d529c to your computer and use it in GitHub Desktop.
Save joshfinley/d98de9be833e2a07befb64e5ae0d529c to your computer and use it in GitHub Desktop.
# Import the Active Directory module if not already loaded
Import-Module ActiveDirectory
# Get the path to the text file from the script arguments
param (
[string]$groupFile
)
# If no path is provided, exit the script
if ([string]::IsNullOrWhiteSpace($groupFile)) {
Write-Output "Please provide the path to the text file."
Exit
}
# Read the group names from the file
$groupNames = Get-Content -Path $groupFile
# Initialize an empty array to store user objects
$users = @()
# Loop through each group and find the users
foreach ($group in $groupNames) {
# Get the AD group
$adGroup = Get-ADGroup -Identity $group -ErrorAction SilentlyContinue
# If the group is found, get the members
if ($null -ne $adGroup) {
$groupMembers = Get-ADGroupMember -Identity $adGroup -Recursive | Where-Object { $_.objectClass -eq 'user' }
# Add each member to the users array
foreach ($user in $groupMembers) {
$userInfo = New-Object PSObject -Property @{
Username = $user.SamAccountName
Name = $user.Name
Group = $group
}
$users += $userInfo
}
}
else {
Write-Output "Group '$group' not found."
}
}
# Output the user objects
$users | Format-Table -Property Username, Name, Group
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment