Home > Back-end >  Format an array inside powershell object
Format an array inside powershell object

Time:01-13

So I have a script that grabs each user and all groups the user belongs in. When I export to a CSV, it has the user in one column, and in the next, all the groups the user is in. Is there anyway to make it where the groups can have their own line each, as opposed to all groups in one cell? This is how the output looks

[user][usergroup a, usergroupb, etc]

and I want

[user][usergroupa]

[ ][usergroupb]

This is my code if anyone wants it:

$users = get-azureaduser -Top 400 | Where-Object{$_.jobtitle -ne $null} |Where-Object{$_.department -eq "Information Technology"} | select userprincipalname
$groups = ForEach($user in $users){
$usergroups = get-azureadusermembership -ObjectId $user.UserPrincipalName | select displayname 

New-Object -TypeName PSObject -Property @{
            User=$user.UserPrincipalName
            Groups = [string]$usergroups.displayname
}
}
$groups | Export-Csv -Path 'C:\TEXTDUMP\usergroups.csv'

CodePudding user response:

You just need an extra foreach loop over the group memberhips:

$users = Get-AzureADuser -Top 400 | Where-Object { $_.jobtitle -ne $null } | Where-Object { $_.department -eq "Information Technology" } | Select-Object -ExpandProperty userprincipalname
$groupMemberships = ForEach ($user in $users) {
    $userGroups = Get-AzureADUserMembership -ObjectId $user | Select-Object -ExpandProperty displayName

    foreach($group in $userGroups){
        New-Object -TypeName PSObject -Property @{
            User   = $user
            Group  = $group
        }
    }
}

$groupMemberships | Export-Csv -Path 'C:\TEXTDUMP\usergroups.csv'

This will produce 1 CSV row per membership, rather than per user

CodePudding user response:

I believe you're looking to expand the data per group, each group per line. If so, you need to loop over the result from Get-AzureADUserMembership:

Get-AzureADUser -Filter "department eq 'Information Technology'" -Top 400 | ForEach-Object {
    if($_.jobTitle) {
        foreach($group in Get-AzureADUserMembership -ObjectId $_.UserPrincipalName) {
            [pscustomobject]@{
                User   = $_.UserPrincipalName
                Groups = $group.DisplayName
            }
        }
    }
} | Export-Csv -Path 'C:\TEXTDUMP\usergroups.csv'

Haven't used the AzureAD Module in a while but I believe the filter:

-Filter "department eq 'Information Technology'"

Should work and be a good replacement for:

Where-Object { $_.department -eq "Information Technology" }
  • Related