forked from 12Knocksinna/Office365itpros
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathReportM365GroupMemberships-Graph.PS1
257 lines (226 loc) · 11.5 KB
/
ReportM365GroupMemberships-Graph.PS1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# ReportM365GroupMemberships-Graph.PS1
# A script to report the membership of all Microsoft 365 Groups in a tenant using Graph calls instead of PowerShell
# https://github.com/12Knocksinna/Office365itpros/blob/master/ReportM365GroupMemberships-Graph.PS1
# Needs the following Graph permissions:
# Group.Read.All, GroupMember.Read.All, User.Read.All
#
#+-------------------------- Functions etc. -------------------------
function Get-GraphData {
# Based on https://danielchronlund.com/2018/11/19/fetch-data-from-microsoft-graph-with-powershell-paging-support/
# GET data from Microsoft Graph.
param (
[parameter(Mandatory = $true)]
$AccessToken,
[parameter(Mandatory = $true)]
$Uri
)
# Check if authentication was successful.
if ($AccessToken) {
$Headers = @{
'Content-Type' = "application\json"
'Authorization' = "Bearer $AccessToken"
'ConsistencyLevel' = "eventual" }
# Create an empty array to store the result.
$QueryResults = @()
# Invoke REST method and fetch data until there are no pages left.
do {
$Results = ""
$StatusCode = ""
do {
try {
$Results = Invoke-RestMethod -Headers $Headers -Uri $Uri -UseBasicParsing -Method "GET" -ContentType "application/json"
$StatusCode = $Results.StatusCode
} catch {
$StatusCode = $_.Exception.Response.StatusCode.value__
if ($StatusCode -eq 429) {
Write-Warning "Got throttled by Microsoft. Sleeping for 45 seconds..."
Start-Sleep -Seconds 45
}
else {
Write-Error $_.Exception
}
}
} while ($StatusCode -eq 429)
if ($Results.value) {
$QueryResults += $Results.value
}
else {
$QueryResults += $Results
}
$uri = $Results.'@odata.nextlink'
} until (!($uri))
# Return the result.
$QueryResults
}
else {
Write-Error "No Access Token"
}
}
# End Functions
CLS
# Check that we are connected to Exchange Online
$ModulesLoaded = Get-Module | Select Name
If (!($ModulesLoaded -match "ExchangeOnlineManagement")) {Write-Host "Please connect to the Exchange Online Management module and then restart the script"; break}
# The need for the Exchange Online module only exists to get the organization name. If you want to hard code this variable, you can eliminate the need to load the EXO module
$OrgName = (Get-OrganizationConfig).Name
$S1 = Get-Date
$Version = "1.0"
$ReportFile = "c:\temp\M365MembersReport.html"
$CSVFileSummary = "c:\temp\M365MembersSummaryReport.csv"
$CSVFileMembers = "c:\temp\M365MembersReport.csv"
$MemberList = [System.Collections.Generic.List[Object]]::new()
$SummaryData = [System.Collections.Generic.List[Object]]::new()
$UserNoGroups = 0; $UserWithGroups = 0
$CreationDate = Get-Date -format g
# Define the values applicable for the application used to connect to the Graph
$AppId = "828e1143-88e3-492b-bf82-24c4a47ada63"
#$AppId = "0ade5c24-d775-4017-a824-0a993c60787c"
$TenantId = "b662313f-14fc-43a2-9a7a-d2e27f4f3478"
#$AppSecret = '7RplGSLWoSs~y4uHYy2041-jbm.4~_r.~q'
$AppSecret = "vAMz95oZ_a9_~dtG_k81UJEK-3Xv.J2X9F"
# Construct URI and body needed for authentication
$uri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
$body = @{
client_id = $AppId
scope = "https://graph.microsoft.com/.default"
client_secret = $AppSecret
grant_type = "client_credentials"
}
# Get OAuth 2.0 Token
$tokenRequest = Invoke-WebRequest -Method Post -Uri $uri -ContentType "application/x-www-form-urlencoded" -Body $body -UseBasicParsing
# Unpack Access Token
$token = ($tokenRequest.Content | ConvertFrom-Json).access_token
$Headers = @{
'Content-Type' = "application\json"
'Authorization' = "Bearer $Token"
'ConsistencyLevel' = "eventual" }
CLS
Write-Host "Fetching user information from Azure Active Directory..."
$Uri = "https://graph.microsoft.com/v1.0/users?&`$select=displayName,usertype,assignedlicenses,id,mail,userprincipalname"
$Users = Get-GraphData -AccessToken $Token -Uri $uri
# Now get rid of all the accounts created for room and resource mailboxes, service accounts etc.
$Users = $Users |?{($_.UserType -eq "Member" -and $_.AssignedLicenses -ne $Null) -or ($_.UserType -eq "Guest")}
# Get a list of Teams and put them into a hash table so that we can mark the groups we process as being team-enabled
$uri = "https://graph.microsoft.com/beta/groups?`$filter=resourceProvisioningOptions/Any(x:x eq 'Team')"
$Teams = Get-GraphData -AccessToken $Token -Uri $uri
$TeamsHash = @{}
$Teams.ForEach( {
$TeamsHash.Add($_.Id, $_.DisplayName) } )
# Set up progress bar
$ProgDelta = 100/($Users.Count); $CheckCount = 0; $UserNumber = 0
ForEach ($User in $Users) {
$UserNumber++
$UserStatus = $User.DisplayName + " ["+ $UserNumber +"/" + $Users.Count + "]"
Write-Progress -Activity "Checking groups for user" -Status $UserStatus -PercentComplete $CheckCount
$CheckCount += $ProgDelta
$UserType = "Tenant user"
# Get Microsoft 365 groups this user is a member of and sort by displayname
$Uri = "https://graph.microsoft.com/v1.0/users/" + $user.id +"/transitiveMemberOf"
$Groups = Get-GraphData -AccessToken $Token -Uri $Uri
$Groups = $Groups | ?{$_.Grouptypes -eq "unified"} | Sort DisplayName
If ($Groups) { # We found some groups for this recipient - process them
$AllGroups = $Groups.DisplayName -Join ", "
$g = 0
ForEach ($Group in $Groups) {
$g++
$Uri = "https://graph.microsoft.com/v1.0/groups/" + $Group.Id + "/owners?"
$GroupData = Invoke-RestMethod -Headers $Headers -Uri $Uri -UseBasicParsing -Method "GET"
If ($GroupData."@odata.count" -eq 0) {
$Owners = "No owners found" }
Else { # Extract owner names
$Owners = $GroupData.Value.DisplayName -join ", " }
If ($TeamsHash[$Group.Id]) { $GroupName = $Group.DisplayName + " (** Team **)" } Else { $GroupName = $Group.DisplayName }
$MemberLine = [PSCustomObject][Ordered]@{ # Write out details of the group
"User" = $User.DisplayName
UPN = $User.UserPrincipalName
"User type" = $User.UserType
"Group Name" = $GroupName
"Group Description" = $Group.Description
"Group Email" = $Group.Mail
"Group Owners" = $Owners }
$MemberList.Add($MemberLine)
} #End For
$SummaryLine = [PSCustomObject][Ordered]@{ # Write out summary record for the user
"User" = $User.DisplayName
UPN = $User.UserPrincipalName
"User type" = $User.UserType
"Groups count" = $g
"Member Of" = $AllGroups }
$SummaryData.Add($SummaryLine)
} # End if
Else { #No groups found for this user, so just write a summary record
$SummaryLine = [PSCustomObject][Ordered]@{
"User" = $User.DisplayName
UPN = $User.UserPrincipalName
"User type" = $UserType
"Groups count" = 0
"Member Of" = "No groups found for user" }
$SummaryData.Add($SummaryLine)
} #End Else
} #End For
$SummaryData = $SummaryData | Sort "Groups Count" -Descending
$GCount = $MemberList | Sort "Group Email" -unique
$UsersNoGroups = ($SummaryData | ? {$_."Groups Count" -eq 0}).Count
$UsersWithGroups = ($SummaryData.Count - $UsersNoGroups)
$S2 = Get-Date
$TotalSeconds = [math]::round(($S2-$S1).TotalSeconds,2)
$SecondsPerUser = [math]::round(($TotalSeconds/$Users.count),2)
# Create the HTML report
$htmlhead="<html>
<style>
BODY{font-family: Arial; font-size: 8pt;}
H1{font-size: 22px; font-family: 'Segoe UI Light','Segoe UI','Lucida Grande',Verdana,Arial,Helvetica,sans-serif;}
H2{font-size: 18px; font-family: 'Segoe UI Light','Segoe UI','Lucida Grande',Verdana,Arial,Helvetica,sans-serif;}
H3{font-size: 16px; font-family: 'Segoe UI Light','Segoe UI','Lucida Grande',Verdana,Arial,Helvetica,sans-serif;}
TABLE{border: 1px solid black; border-collapse: collapse; font-size: 8pt;}
TH{border: 1px solid #969595; background: #dddddd; padding: 5px; color: #000000;}
TD{border: 1px solid #969595; padding: 5px; }
td.pass{background: #B7EB83;}
td.warn{background: #FFF275;}
td.fail{background: #FF2626; color: #ffffff;}
td.info{background: #85D4FF;}
</style>
<body>
<div align=center>
<p><h1>Microsoft 365 Groups and Teams Membership Listing</h1></p>
<p><h2><b>All groups in the " + $Orgname + " organization</b></h2></p>
<p><h3>Generated: " + (Get-Date -format g) + "</h3></p></div>"
$htmlbody1 = $MemberList | ConvertTo-Html -Fragment
$htmlbody1 = $htmlbody1 + '<div class="page-break"></div>'
$htmlbody2 = $SummaryData | ConvertTo-Html -Fragment
$htmltail = "<p>Report created for: " + $OrgName + "</p>" +
"<p>Created: " + $CreationDate + "<p>" +
"<p>-----------------------------------------------------------------------------------------------------------------------------</p>"+
"<p>Number of users in groups: " + $UsersWithGroups + "</p>" +
"<p>Number of users not in groups: " + $UsersNoGroups + "<p>"+
"<p>Number of Microsoft 365 Groups: " + $GCount.Count + "</p>" +
"<p>Number of Microsoft Teams: " + $Teams.Count + "</p>" +
"<p>-----------------------------------------------------------------------------------------------------------------------------</p>"+
"<p>Microsoft 365 Group Membership Report (Graph)<b>" + $Version + "</b>"
$htmlreport = $htmlhead + $htmlbody1 + "<p><p>" + $htmlbody2 + $htmltail
$htmlreport | Out-File $ReportFile -Encoding UTF8
$MemberList | Export-CSV -NoTypeInformation $CSVFileMembers
$SummaryData | Export-CSV -NoTypeInformation $CSVFileSummary
CLS
Write-Host "Microsoft 365 Group Membership Report (Graph Version) - Job Complete"
Write-Host "--------------------------------------------------------------------"
Write-Host " "
Write-Host "Outputs:"
Write-Host "--------"
Write-Host "HTML report available in" $ReportFile
Write-Host " "
Write-Host "Contains all the data generated by the script."
Write-Host " "
Write-Host "CSV file for members in groups available in" $CSVCileMembers
Write-Host " "
Write-Host "Lists details of group membership for individual user accounts."
Write-Host " "
Write-Host "CSV summary report available in" $CSVFileSummary
Write-Host " "
Write-Host "Summarizes the groups that users belong to."
Write-Host " "
Write-Host ("Total processing time {0} seconds ({1} seconds per user) for {2} user accounts and {3} Microsoft 365 Groups" -f $TotalSeconds, $SecondsPerUser, $Users.Count, $Gcount.count)
# An example script used to illustrate a concept. More information about the topic can be found in the Office 365 for IT Pros eBook https://gum.co/O365IT/
# and/or a relevant article on https://office365itpros.com or https://www.petri.com. See our post about the Office 365 for IT Pros repository # https://office365itpros.com/office-365-github-repository/ for information about the scripts we write.
# Do not use our scripts in production until you are satisfied that the code meets the need of your organization. Never run any code downloaded from the Internet without
# first validating the code in a non-production environment.