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
Advertisements

PowerShell Script: Search and Delete Active Directory Users who have been inactive for 180 days

## Search Users that have been inactive for 180 days.
Search-ADAccount -AccountInactive -TimeSpan 180 | Select-Object Name, LastLogonDate, DistinguishedName, SamAccountName | Export-Csv C:\Temp\NoExpiration2016.csv

## Delete Users from the above script
Import-CSV C:\Temp\NoExpiration2016.csv | ForEach-Object {Remove-ADUser -Identity $SamAccountName -Confirm:$False}