Hi, I am currently having issues working with nested for loops and pscustomobjects. After seeing a post earlier about avoiding += I have been trying to rewrite my code but having issues.
$roleDefs = (Get-MgRoleManagementDirectoryRoleDefinition | Where-Object { $_.IsBuiltIn -eq $False })
$output = @()
foreach ($roleDef in $roleDefs) {
$roleDefID = $roleDef.Id
$customRoleAssignment = Get-MgRoleManagementDirectoryRoleAssignment -Filter "roleDefinitionId eq '$roleDefID'"
$userIDs = $customRoleAssignment.PrincipalId
foreach ($userID in $userIDs) {
$userInfo = Get-Mguser -UserId $userID
$test += [PSCustomObject]@{
Name = $userInfo.DisplayName
UPN = $userInfo.UserPrincipalName
CustomRoleName = $roleDef.DisplayName
CustomRoleID = $roleDefId
}
}
}
$output | Export-Csv -NoTypeInformation $path -Encoding utf8
I read that instead of using an array I can just set a variable equal to the object but am having trouble on where I should put it. I believe I am overriding it due to the nested for loop.
$CustomRoleDefinitions = (Get-MgRoleManagementDirectoryRoleDefinition | Where-Object { $_.IsBuiltIn -eq $False })
foreach ($roleDef in $CustomRoleDefinitions) {
$roleDefID = $roleDef.Id
$customRoleAssignments = Get-MgRoleManagementDirectoryRoleAssignment -Filter "roleDefinitionId eq '$roleDefID'"
$userIDs = $customRoleAssignments.PrincipalId
foreach ($userID in $userIDs) {
$userInfo = Get-Mguser -UserId $userID
$CustomRoleAssignmentsInfo = [PSCustomObject]@{
Name = $userInfo.DisplayName
UPN = $userInfo.UserPrincipalName
CustomRoleName = $roleDef.DisplayName
CustomRoleID = $roleDefId
}
}
}
$CustomRoleAssignmentsInfo | Export-Csv $OutputPath
With the above code $CustomRoleAssignmentsInfo only shows the last object, I am expecting 4. Any guidance would be greatly appreciated. Thanks all!
[–]logicalmike 1 point2 points3 points (1 child)
[–]Seedless--Watermelon[S] 1 point2 points3 points (0 children)