I am having issues getting this to work with all AD groups. Some groups return what I am looking for but the Termination OU is not returning anything. What may I be missing?
#Set target OU
$GroupsOU = "DC=fake,DC=local"
import-module ActiveDirectory
$Searchterm = read-host -Prompt "type the group name to export and press enter. Be precise, as the search will be *text* against the name (not DN)."
#Set export location, remove if exists
$exportpath = ([environment]::getfolderpath("desktop") + "\GroupMatchMemberExport" + $Searchterm + ".csv")
$FilePathTest = test-path -Path $exportpath
if ($FilePathTest) {remove-item -path $exportpath}
#Prep Export object Array
$ExportArray = @()
#Get all groups with name similar to searchterm
$MatchedGroups = get-adgroup -filter "name -like '*$searchterm*'" -SearchBase $GroupsOU -Properties name, sid, DESCRIPTION, objectGUID
#For each group, get members, and iterate through, adding each with group details
foreach ($group in $MatchedGroups)
{
#Get all group members
$GroupMembers = get-adgroupmember -identity $group.objectGUID -Recursive
#Iterate through grabbing the SAM and exporting with the group name, descrcription, and sid
foreach ($user in $GroupMembers)
{
#Grab user details
$TargetMember = get-aduser -filter {name -like $user.name} -Properties SamAccountName, UserPrincipalName, givenname, surname, name, distinguishedname, sid
#Add to export array
write-host ('Adding information for ' + $TargetMember.SamAccountName + ' to export array. ')
$ExportObject = New-Object System.Object
$ExportObject | Add-Member -MemberType noteproperty -force -Name "Path" -Value $group.DESCRIPTION
$ExportObject | Add-Member -MemberType noteproperty -force -Name "GroupNAME" -Value $group.name
$ExportObject | Add-Member -MemberType noteproperty -force -Name "GroupSID" -Value $group.sid
$ExportObject | Add-Member -MemberType noteproperty -force -Name "User Name" -Value ($TargetMember.givenname + ' ' + $TargetMember.surname)
$ExportObject | Add-Member -MemberType noteproperty -force -Name "SAMaccountname" -Value $TargetMember.SamAccountName
$ExportObject | Add-Member -MemberType noteproperty -force -Name "UsesPrincipleName" -Value $TargetMember.UserPrincipalName
$ExportObject | Add-Member -MemberType noteproperty -force -Name "distinguishedname" -Value $TargetMember.distinguishedname
$ExportObject | Add-Member -MemberType noteproperty -force -Name "UserSID" -Value $TargetMember.sid
#add object to array
$ExportArray += $exportObject
}
}
#Export
write-host "Exporting pending values.."
$ExportArray | Export-Csv -path $exportpath -NoTypeInformation
write-host "Process complete. Press enter to exit.. "
Read-Host