Problem Break-Down
So I'm trying to return a list of all the security user groups a user is in but have it be broken up by manager. I take a couple of steps to do this:
- Get all users into UserList
- Gather a list of managers using the list of users.
- Sort the list of managers into a unique list.
- Get Manager SamAccountNames.
- Get directreports attribute from the managers to create the list of subordinates.
- Get their SamAccountNames
- Use SamAccountNames to pull AD Security Groups and Descriptions.
Everything works when used in little pieces. If you declare some names for $DirectReports and then run the final for loop it returns everything appropriately.
When running the script however, it returns only the Manager name, the direct report name, and all the lines for the security groups but nothing is in the lines for the security groups.
No relevant error message. Thanks in advance for the help.
Code
#Search Organizational Unit to find all Users
$UserList = @(Get-ADUser -Filter * -SearchBase "COMPANY'S ORG UNITS").SamAccountName
#For every user found in OU, select their manager
foreach ($User in $UserList) {
$Manager = @(Get-ADUser $User -Properties * | Select-Object @{Name = "Manager";Expression = {($_.manager -split ',*..=')[1]}})
$Managers += $Manager
}
#Sort and Select Unique Managers
$Managers = $Managers | Sort-Object -Property Manager -Unique
#Get SamAccountName From Manager Name
for ($a = 0; $a -lt $Managers.Count; $a++) {
$FilterString = "Name -eq '{0}'" -f $Managers[$a].Manager
$SAM = @(Get-ADUser -Filter "$FilterString" | Select SamAccountName)
$SAMs += $SAM
}
#Get subordinates for each manager
for ($b=0; $b -lt 1; $b++) {
#Get direct reporting individuals, second line cleans up output.
$DirectReports = @(Get-ADUser $SAMs[$b].SamAccountName -Properties directreports | select-object -ExpandProperty DirectReports)
$DirectReports = $DirectReports -replace "(CN=)(.*?),.*",'$2'
$Managers[$b+1]
Write-Output "`n"
#Get SAM names for direct reporting individuals and use to get user properties
for ($c = 0; $c -lt $DirectReports.Count; $c++) {
$FilterString2 = "Name -eq '{0}'" -f $DirectReports[$c]
$DirectReports[$c]
$SAM2 = @(Get-ADUser -Filter "$FilterString2")
$SAM2.SamAccountName
Get-ADPrincipalGroupMembership -Identity $SAM2.SamAccountName | Get-ADGroup -Properties * | select name, description
Write-Output "`n"
}
}
Format-Tableformatting is applied, which happens implicitly if an object has 4 or fewer properties, the first object in a collection locks in all display columns based on its properties. If subsequent objects have different properties, only those they share with the first one are displayed; if a given object shares none, a blank line is displayed. This is only a display problem, as you can verify by piping the objects to... | Format-List. See this answer for more information.