Netflex Blog

Show Active Directory Group Membership

powershell

Sometimes it could be handy to save all members of an AD group to a text file.
This simple script will display all members of an Active Directory group on screen and mail the result to the logged in user (user@domain.com) if desired.

show-active-directory-group-membership

<# Author: Michiel Elderson (Netflex)
Date: 01-07-2016
Purpose: Show Active Directory Group Members
Usage: Change the $Logfile location as desired and customize the SMTP
settings to reflect your environment Run this file in Powershell
History Version |Date |Name |Comments 1.0 |01-07-2016 |Michiel Elderson |Initial Version #>

param(
[parameter(Position=0,Mandatory=$true,ValueFromPipeline=$false,
HelpMessage='Group to retrieve the members from')][string]$AdGroup

)

Import-Module ActiveDirectory

#Delete report if exists
$Logfile = "D:\UserGroupMembership.log"
If (Test-Path $Logfile){
del $Logfile
}

#Set email settings
$From = "NoReply@domain.com"
$subject = "LogFile Users $AdGroup"
$SmtpServer = "SMTPserver.domain.com"
$MailDomain = "domain.com"
$body = "Group members $AdGroup"
$attachement = $logfile
$AdminUser = [environment]::username

write-host "Collecting group members..." -ForegroundColor Yellow
Get-AdGroupMember -Identity $adGroup | ft SAMACCOUNTNAME,NAME -autosize | Out-File $Logfile
Get-Content $logfile

$title = "Logfile mailen naar $AdminUser ?"
$No = New-Object System.Management.Automation.Host.ChoiceDescription "&No", `
"Do not mail the logfile."
$Yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", `
"Mail Logfile to curent user"

$options = [System.Management.Automation.Host.ChoiceDescription[]]($No, $Yes)
$result = $host.ui.PromptForChoice($title, $message, $options, 1)

switch ($result)
{
0 {return
}

1 {Send-mailmessage -to $adminuser@$Maildomain -from $From -subject $Subject -Body $Body -SmtpServer $SmtpServer -Attachments $attachement
Write-host "Logfile send.." -ForegroundColor green
}

}

Usage:
Change the $Logfile location as desired and customize the SMTP settings to reflect your environment
Start the script from Powershell and provide an Active Directory group name.

Download the script by clicking here.

Scroll to Top