Export AzureAD group owners to CSV - powershell

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

Figured it out with some help from other sources. Hopefully someone will find this helpful in future! This is how:
#Connect to AzureAD
Connect-AzureAD
$Properties=#{}
$matchingOwners=#()
$groups = Get-AzureADGroup -All $true | Where-Object DisplayName -Like "*Guest*"
Foreach($group in $groups) {
$Owners = Get-AzureADGroupOwner -ObjectId $group.ObjectId -All $true
     $matchingGroup = $group.DisplayName
if ($null -ne $Owners) {
#group has owner
Foreach($Owner in $Owners) {
                $matchingOwners+=$Owner.DisplayName
}
}
$joinedOwners = $matchingOwners -join ", "
     $Properties.add($matchingGroup, $joinedOwners)
$joinedOwners=""
$matchingOwners=#()
}
$Properties.GetEnumerator() | Select-Object -Property Key,Value | Sort-Object -Property Key | export-csv -Path C:\Temp\test123.csv -NoTypeInformation -Encoding UTF8
#Disconnect from AzureAD
Disconnect-AzureAD

I tried to reproduce the same in my environment by using the below PowerShell script:
$array = #()
$Properties=#{}
$Properties.add("GroupDisplayName","1")
$Properties.add("OwnerObjectId","2")
$Properties.add("OwnerObjectType","3")
$Properties.add("OwnerUserType","4")
$Properties.add("OwnerUserPrincipalName","5")
$groups = Get-AzureADGroup -All $true
Foreach($group in $groups){
$Owners = Get-AzureADGroupOwner -ObjectId $group.ObjectId -All $true
ForEach ($Owner in $Owners){
$Properties.GroupDisplayName=$group.DisplayName
$Properties.OwnerObjectId=$Owner.ObjectId
$Properties.OwnerObjectType=$Owner.ObjectType
$Properties.OwnerUserType=$Owner.UserType
$Properties.OwnerUserPrincipalName=$Owner.UserPrincipalName
$obj=New-Object PSObject -Property $Properties
$array +=$obj
}
}
$array | export-csv -Path YourPath.csv -NoTypeInformation -Encoding UTF8
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

Related

Create csv file of all disabled AD users with mailboxes Output information from multiple cmdlets in powershell

I am trying to gather some information on disabled user accounts that have mailboxes. I am specifically looking for just user mailboxes not shared mailboxes.
Here is what I have so far.
$Mailboxes = Get-Mailbox | where {$_.RecipientTypeDetails -eq 'UserMailbox'}
$date = get-date -f "MMddyyyy_HHmm"
$Disabled = #()
Foreach ($Mailbox in $Mailboxes) {
if((Get-ADUser -Identity $Mailbox.SamAccountName).Enabled -eq $False){
$Disabled += Get-MailboxStatistics $Mailbox.SamAccountName | Select -Property DisplayName,TotalItemSize
}
}
$Disabled | Sort DisplayName | Export-Csv -Path "%path%\DisabledADUsersWithMailbox_$date`.csv" -NoTypeInformation
Additionally what I would like to collect is the users Title, Manager, LastlogonDate all of which can be found using Get-Aduser. I am unsure how I go about collecting the information from both cmdlets and then exporting it all to csv. I have read that I may need to create a custom object. I am struggling with setting that up in this script.
Any help would be much appreciated.
Thanks
the following lines should give you what you want, can't verify it as I have no exchange running here.
$date = get-date -f "MMddyyyy_HHmm"
$Disabled = #(
Foreach ($Mailbox in $Mailboxes) {
$adUser = get-aduser -Identity $Mailbox.SamAccountName -Properties enabled,manager,title,lastlogontimestamp
If ($adUser.Enabled -eq $False){
$mailStats = Get-MailboxStatistics $Mailbox.SamAccountName
$attrsht = [ordered]#{
displayname=$mailstats.displayname
totalitemsize=$mailStats.totalitemsize
samaccountname=$aduser.samaccountname
enabled=$aduser.enabled
manager=$aduser.manager
title=$aduser.title
lastlogontimestamp=[datetime]::FromFileTime($aduser.lastlogontimestamp)
}
new-object -TypeName psobject -Property $attrsht
}
}
)
$Disabled | Sort-Object DisplayName | Export-Csv -Path "%path%\DisabledADUsersWithMailbox_$date`.csv" -NoTypeInformation
Avoid adding elements to an array by using +=. It is slow, alternatively take a look at generic array lists.

Export users not in an office 365 security group

I need to find users that are not in a office 365 security group. I'm not sure how to proceed after getting the list of all the users in the tenant.
This works for pulling a list of users
Get-MSOLUser -all | Where-Object { $_.isLicensed -eq "True"} | Select-Object UserPrincipalName | Export-Csv -path .\users.csv
I'm not sure where to go from here.
This is something like what I'm looking for.
Get-MSOLUser -all | Where-Object { $_.isLicensed -eq "True",-and $_.isNotMemberofGroup "SecurityGroup"} | Select-Object UserPrincipalName | Export-Csv -path .\users.csv
I don't have a way of testing this but this should be the logic you should follow with this pre-historic module, first get the list of members of your target group (in this case ExampleGroup) and then you can loop over all the users filtering by both conditions:
The user has a License
The user is not a member of the Target Group
$targetGroup = "ExampleGroup"
$groupMembers = Get-MsolGroup $targetGroup | Get-MsolGroupMember
Get-MsolUser -All | ForEach-Object {
if($_.isLicensed -eq $true -and $_.ObjectId -notin $groupMembers.ObjectId) {
$_
}
} | Select-Object UserPrincipalName | Export-Csv -Path .\users.csv
the Cmdlets do not natively provide such features but with PowerShell we can use Compare-Object to check differences between two object arrays:
Fetch all users: $allUsers = Get-MSOLUser -all
Fetch members of your group: $groupMembers = Get-MsolGroupMember -GroupObjectId <Your-Group-ID>
Compare the two arrays: Compare-Object -ReferenceObject $groupMembers -DifferenceObject $allUsers -Property ObjectId
Based on your needs you can filter the above based on the SideIndicator property
Export the results by piping the above with | Export-CsV ...
I wasn't able to get the answer to work for me. Perhaps this works for others.
$targetGroup = "ExampleGroup"
$groupMembers = Get-MsolGroupMember -groupobjectid $targetGroup
Get-MsolUser -All | ForEach-Object {
if($_.isLicensed -eq $true -and $_.ObjectId -notin $groupMembers.ObjectId) {
$_
}
} | Select-Object UserPrincipalName | Export-Csv -Path .\users.csv

how to list users and the groups they are part of in office 365 powershell

i need a script please to export users in office 365 and the groups they are part of and not the other way around. can anyone help please. all answers i found were to export distribution groups and their members.
i tried using the below but i dont know how to select group names.
get-mailbox | ? {$_.PrimarySMTPAddress -like "*domain.com"} | Select DisplayName,Alias,PrimarySMTPAddress'
and i tried this too
get-mailbox | ? {$_.PrimarySMTPAddress -like "*domain.com"} | Sort Name | % { $MbxDirData = $_ ; Get-MailboxStatistics $_ } | Select DisplayName, #{E={ $MbxDirData.Alias };L='Alias'}, #{E={ $MbxDirData.PrimarySMTPAddress };L='PrimarySMTPAddress'}, #{E={ $_.TotalItemSize.Value + $_.TotalDeletedItemSize.Value };L="TotalMailboxSize"}
any help is appreciated.
This is untested, but I think you can use cmdlets Get-User and then Get-Group to retrieve the groups a user is a member of like this:
Get-Mailbox | Where-Object {$_.PrimarySMTPAddress -like "*domain.com"} | ForEach-Object {
$user = Get-User -Identity $_.DistinguishedName
$groups = Get-Group | Where-Object {$_.Members -contains $User}
$_ | Select-Object DisplayName, Alias, PrimarySMTPAddress,
#{Name = 'Groups' ; Expression = {$groups.Name -join '; '}}
} | Export-Csv -Path 'X:\O365UserGroups.csv' -NoTypeInformation
The above concatenates the groups with a semi-colon in one single field of the CSV, but if you would rather have output where there is one line for each group, you can do:
Get-Mailbox | Where-Object {$_.PrimarySMTPAddress -like "*domain.com"} | ForEach-Object {
$user = Get-User -Identity $_.DistinguishedName
$groups = Get-Group | Where-Object {$_.Members -contains $User}
# output a data row for each group in the collection
foreach ($group in $groups) {
$_ | Select-Object DisplayName, Alias, PrimarySMTPAddress,
#{Name = 'Groups' ; Expression = {$group.Name}}
}
} | Export-Csv -Path 'X:\O365UserGroups.csv' -NoTypeInformation
We can list all the office 365 groups by using the PowerShell cmdlet Get-UnifiedGroup and its group members by Get-UnifiedGroupLinks cmdlet .
You can use the below PowerShell script ,which will Export All Office 365 Group Members to csv. We have tested this in our local environment which is working fine.
$Groups = Get-UnifiedGroup -ResultSize Unlimited
$Groups | ForEach-Object {
$group = $_
Get-UnifiedGroupLinks -Identity $group.Name -LinkType Members -ResultSize Unlimited | ForEach-Object {
New-Object -TypeName PSObject -Property #{
Group = $group.DisplayName
Member = $_.Name
EmailAddress = $_.PrimarySMTPAddress
RecipientType= $_.RecipientType
}}} | Export-CSV "C:\Office365GroupMembers.csv" -NoTypeInformation -Encoding UTF8
Here is the sample output screenshot for reference :
Note:
Get-UnifiedGroup cmdlet is available only in the cloud-based service.
For more Information you refer this blog post & also if you faces any issues while executing Get-unifiedGroup cmdlet you refer this .

Export azure ad groups membership via powershell

I need help in the powershell script. I am looking to get Azure AD, group membership details for multiple groups which are in the CSV file.
The format, I am looking to get is:
Group Name :SG-Test-Users
Members: xyz, abc etc
Output needed in this format
Please help
I tried, below script but it is not giving an output in the format I am looking for.
Import-Csv -Path "C:\temp\testgroup.csv" | ForEach-Object {Get-AzureADGroupMember -ObjectId $_.name | select displayname,userprincipalname} | Export-Csv -Path "c:\temp\outputfile1.csv" -NoTypeInformation
Thanks,
Try the command below, it works fine on my side. Note it will append data to the file instead of overwriting.
$csv = Import-Csv "C:\Users\joyw\Desktop\testgroup.csv"
foreach ($line in $csv){
$groupname = $line.GroupName
$objectid = (Get-AzureADGroup | Where-Object {$_.DisplayName -eq $groupname}).ObjectId
Get-AzureADGroupMember -ObjectId $objectid | select DisplayName,UserPrincipalName | Export-Csv -Path "C:\Users\joyw\Desktop\outputfile1.csv" -NoTypeInformation -Append
}
My test file:
testgroup.csv
outputfile1.csv
I'm new to this, but here's my take
try below (modify output as required) and then save the console output to file and massage as required in excel
cheers
$gg=Get-AzureADGroup -top 200
ForEach ($g in $gg){
$a = Get-AzureADGroup -ObjectId $g.ObjectId
$b = Get-AzureADGroupMember -ObjectId $g.ObjectId -All $true
ForEach ($c in $b){
Write-host $a.DisplayName ";" $c.ObjectId ";" $c.ObjectType $c.UserType ";" $c.UserPrincipalName
}
}
$ResourceAuditArray = #()
ForEach ($g in Get-AzureADGroup -SearchString "<first word of groups e.g. DFC, ADF, DAS>"){
$ResourceAuditArray += Get-AzureADGroupMember -ObjectId $g.ObjectId -All $true | Select-Object ObjectId, ObjectType, UserType, UserPrincipalName, #{n="DisplayName"; e={$g.DisplayName}}
}
$ResourceAuditArray | Export-Csv "<AAD Users list>.Csv"

Create dynamic members of PSObject

This is what I got:
Import-Module ActiveDirectory
$objectCollection = #()
$groups = (Get-ADGroup -Filter *)
foreach ($group in $groups) {
$groupName = ($group.SamAccountName)
$object = (New-Object –Type PSObject)
Add-Member -InputObject $object -MemberType NoteProperty –Name ($groupName) –Value ""
$groupMembers = (Get-ADGroupMember -Identity "$groupName" -Recursive |
Select-Object -ExpandProperty Name)
$object.$groupName = $groupMembers
$objectCollection += $object
}
$objectCollection | Export-Csv -Path C:\Users\administrator\Desktop\test.csv `
-Encoding UTF8 -Delimiter ";" -NoTypeInformation
The goal with this script is to create a CSV file where the AD group name is the header in one column an then all the members of the group listed below on separate lines. Next group is in a new column with the AD-group name as header and so on...
Normally I create as many Members as I need but this time I want it to be dynamic to how many groups there is and the script above only displays the first group in the $groups array.
Any help is appreciated, thanks in advance!
Having each group on a separate column in a CSV file seems illogical to me ; one on each row would IMHO be better (and easier too).
Here is how I would do it:
Import-Module ActiveDirectory
Get-ADGroup -Filter * | ForEach-Object {
[PSCustomObject]#{
Name = $_.samAccountName
Members = (Get-ADGroupMember $_ -Recursive | Select-Object -ExpandProperty Name) -join ","
}
} | Export-Csv -Path "C:\Users\administrator\Desktop\test.csv" -Encoding UTF8 -Delimiter ";" -NoTypeInformation
Output:
"Name";"Members"
"Administrators";"Administrator,..."
"Domain Users";"Administrator,TestUser,..."