PowerShell Script: List all Users in a Security Groups

A question that’s been popping up here and there is “How can I list all users in a security group?” This script is part of a larger script, but this part might be helpful to showcase how we can solve this using powershell.

Import-Module ActiveDirectory
$date = get-date -UFormat "%Y%m%d"
##Example ="OU=Company,DC=Cisco,DC=local"
$Groupaccountpath = "OU=Company,DC=Cisco,DC=local"
$Groups = (Get-AdGroup -filter * -SearchBase $Groupaccountpath | Where {$_.name -like "**"} | select name -ExpandProperty name)
$Table = @()
$Record = @{
  "Group Name" = ""
  "Name" = ""
  "Username" = ""

Foreach ($Group in $Groups) {
  $Arrayofmembers = Get-ADGroupMember -identity $Group -recursive | get-aduser | Where {$_.Enabled -eq $true}  | select name,samaccountname
  foreach ($Member in $Arrayofmembers) {
    $Record."Group Name" = $Group
    $Record."Name" = $Member.name
    $Record."UserName" = $Member.samaccountname
    $objRecord = New-Object PSObject -property $Record
    $Table += $objrecord
$Table | export-csv "C:\temp\SecurityGroups_$date.csv" -NoTypeInformation

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s