The end goal I'm after is I want to have a csv containing the owners of all AzureAD groups.
I'm not well versed in PS and I've been trying to crack it for a while now, with various different scripts each with their own method. Things that seem logical, and I think would work, don't.
Feel free to edit what I've got or write a new script entirely, but please explain what you have done so I can learn :)
The closest I've come to what I want is using the below. But the caveat is if there are multiple owners of the group, each owner is listed out on separate rows and so there is also duplicate group names. I would like to have the group name in one column then all the owners in the next, seperated by " ,".
I tried using -join on the final line but it returns blank results.
$array = @()
$Properties=@{}
$Properties.add("GroupDisplayName","1")
$Properties.add("OwnerDisplayName","2")
$groups = Get-AzureADGroup -All $true | Where-Object DisplayName -Like "*Guest*" | Sort-Object -Property DisplayName
Foreach($group in $groups){
$Owners = Get-AzureADGroupOwner -ObjectId $group.ObjectId -All $true
$Properties.GroupDisplayName=$group.DisplayName
if($Owners -ne $null){
# group has owner
Foreach($Owner in $Owners){
$Properties.OwnerDisplayName=$Owner.DisplayName
$obj=New-Object PSObject -Property $Properties
$array +=$obj
}
}
else{
#group has no owner
$Properties.OwnerDisplayName=$null
$obj=New-Object PSObject -Property $Properties
$array +=$obj
}
}
$array | export-csv -Path C:\Temp\test123.csv -NoTypeInformation -Encoding UTF8
Thanks in advance for your help, you will save me some hair...
EDIT This is another route I've tried. It does return results I want if using one specific ObjectID but I can't get it to loop the bunch of ObjectIds from step 1 and run the command for each one.
#Connect to AzureAD
Connect-AzureAD
#Successfully returns groups with "Guest" in DisplayName
$GroupSearch = Get-AzureADGroup -All $true | Where-Object DisplayName -Like "*Guest*" | Select-Object ObjectId, DisplayName | Sort-Object -Property DisplayName
$groups = @($GroupSearch | Select-Object ObjectID)
#Now to loop ObjectIDs from STEP 1 to lookup command
$Result = foreach ($group in $groups){
Get-AzureADGroupOwner -ObjectId "$group" | Select-Object DisplayName
}
$Result | Export-Csv -Path "C:\Temp\AzureADgroupOwners.csv" -NoTypeInformation
#Disconnect from AzureAD
Disconnect-AzureAD
I tried to reproduce the same in my environment by using the below PowerShell script:
The above script got executed successfully as below:
The CSV file was exported with the Azure Ad Group and Group owner details like below:
Reference:
powershell - Export all Azure AD Groups and their owner to a csv file by Jim Xu