content.php

Powershell Script – Get members of a group

One critical and often requested task is to be able to produce a csv list of members of an AD group.

Import-Module ActiveDirectory

$ou = "DC=YOURDOMAIN, DC=com"
$csvfile = "C:\Location\Filename.csv"

#create a new file if it doesn't exist already
$headers = "DisplayName", "SAMAccountName","LastLogon"
$psObject = New-Object psobject
foreach($header in $headers)
{
   Add-Member -InputObject $psobject -MemberType NoteProperty -Name $header -Value ""
}
$psObject | Export-Csv $csvfile -NoTypeInformation

$properties "DisplayName", "SAMAccountName", "LastLogon"
$groupUsers = Get-ADGroupMember -Identity "Your GroupName" -Recursive | Get-ADUser -Properties $properties

foreach($user in $groupUsers){
    $displayname = $user.DisplayName
    $samact = $user.SamAccountName
    $lastlg = $user.LastLogonDate

    $hash = @{
      "DisplayName" = $displayname
      "SAMAccountName" = $samact
      "LastLogon" = $lastlg
    }
$newRow = New-Object PsObject -Property $hash
Export-Csv $csvfile -inputobject $newRow -apppend -Force
echo $newRow
}

Leave a Reply

Your email address will not be published. Required fields are marked *