forked from junecastillote/Ms365UsageReport
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGet-Ms365UsageReport.ps1
1265 lines (1103 loc) · 66.6 KB
/
Get-Ms365UsageReport.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#Requires -Version 5.1
#Requires -PSEdition Desktop
#Requires -Modules @{ ModuleName="MSAL.PS"; ModuleVersion="4.16.0.4" }
#Requires -Modules @{ ModuleName="ExchangeOnlineManagement"; ModuleVersion="2.0.3" }
#Requires -Modules @{ ModuleName="powershell-yaml"; ModuleVersion="0.4.2" }
<#PSScriptInfo
.VERSION 1.2.8
.GUID 0a5697c4-b4d6-470b-a851-50727da79de8
.AUTHOR June Castillote
.COMPANYNAME June Castillote
.COPYRIGHT [email protected]
.TAGS
.LICENSEURI
.PROJECTURI https://github.com/junecastillote/Ms365UsageReport
.ICONURI
.EXTERNALMODULEDEPENDENCIES
.REQUIREDSCRIPTS
.EXTERNALSCRIPTDEPENDENCIES
.RELEASENOTES
Include:
* [√] Reports > Usage > Active Users
* [√] Reports > Usage > Activations > Users
Add Config item:
* [√] tenantName
* [√] msGraphAuthType
* [√] msGraphAppID
* [√] msGraphAppKey
* [√] msGraphAppCertificateThumbprint
* [√] exchangeAuthType
* [√] exchangeAppID
* [√] exchangeAppCertificateThumbprint
* [√] exchangeCredentialFile
Changed:
* [√] Revert Get-ExoMailbox to Get-Mailbox due to REST-related issues.
Icons: https://www.iconfinder.com/iconsets/logos-microsoft-office-365
.PRIVATEDATA
#>
<#
.SYNOPSIS
Short description
.DESCRIPTION
Microsoft 365 Usage Reporting Script using Microsoft Graph API and Exchange Online PowerShell V2
.EXAMPLE
PS C:\> .\Get-Ms365UsageReport.ps1 -Config .\config.yml
.INPUTS
Inputs (if any)
.OUTPUTS
Output (if any)
.NOTES
General notes
#>
[cmdletbinding()]
param (
[Parameter(Mandatory)]
[string]$Config
)
#Region Functions
Function LogEnd {
$txnLog = ""
Do {
try {
Stop-Transcript | Out-Null
}
catch [System.InvalidOperationException] {
$txnLog = "stopped"
}
} While ($txnLog -ne "stopped")
}
Function LogStart {
param (
[Parameter(Mandatory = $true)]
[string]$logPath
)
LogEnd
Start-Transcript $logPath -Force | Out-Null
}
#EndRegion Functions
While (Get-PSSession -Name ExchangeOnline*) {
Disconnect-ExchangeOnline -Confirm:$false -ErrorAction SilentlyContinue
}
LogEnd
#Enable TLS 1.2
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$WarningPreference = "SilentlyContinue"
$script_root = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition
$scriptInfo = Test-ScriptFileInfo -Path $MyInvocation.MyCommand.Definition
$styleFolder = "$($script_root)\style"
$resourceFolder = "$($script_root)\resource"
$logoFile = "$($resourceFolder)\logo.png"
$officeIconFile = "$($resourceFolder)\office.png"
$exchangeIconFile = "$($resourceFolder)\exchange.png"
$sharepointIconFile = "$($resourceFolder)\sharepoint.png"
$onedriveIconFile = "$($resourceFolder)\onedrive.png"
$skypeIconFile = "$($resourceFolder)\skype.png"
$teamsIconFile = "$($resourceFolder)\teams.png"
$settingsIconFile = "$($resourceFolder)\settings.png"
$defenderIconFile = "$($resourceFolder)\defender.png"
# $headerParams = @{'Authorization' = "Bearer $($GraphApiAccessToken)" }
# Create transcript folder
$logFolder = "$($script_root)\transcript"
$logFile = "$($logFolder)\log_$(Get-Date -Format dd-MMM-yyyy_H_mm_ss).txt"
if (!(Test-Path $logFolder)) {
Write-Output "$(Get-Date) : Creating Transcript folder $($logFolder)"
New-Item -ItemType Directory -Path $logFolder -Force | Out-Null
}
#region config
# Import configuration
try {
$Config = (Resolve-Path $Config -ErrorAction STOP).Path.ToString()
}
catch {
Write-Output "$(Get-Date) : [X] Cannot open the configuration file. Make sure that the file is accessible and valid."
LogEnd
return $null
}
$options = Get-Content $Config -Raw | ConvertFrom-Yaml
$transLog = $options.parameters.transLog
Write-Output "$(Get-Date) : Using configuration from $($Config)"
$enabledReport = @()
# Show or Hide Logo
$showLogo = $options.parameters.showLogo
# Select reports from config
# Parameters
$saveRawData = $options.parameters.saveRawData
# Developer
$graphApiVersion = $options.developer.graphApiVersion
# License
$reportLicenseAssigned = $options.reports.license
if ($reportLicenseAssigned) { $enabledReport += "License" }
# MS365 Active Users
$reportMs365ActiveUsers = $options.reports.ms365ActiveUsers
if ($reportMs365ActiveUsers) { $enabledReport += "User" }
# MS365 Activation
$reportMs365ActivationUsers = $options.reports.ms365ActivationUsers
if ($reportMs365ActivationUsers) { $enabledReport += "Activation" }
# Exchange
$reportMailboxUsageAndProvisioning = $options.reports.exchangeMailbox
$reportOffice365GroupsProvisioning = $options.reports.Office365Groups
$reportEmailAppUsage = $options.reports.exchangeApp
$reportMailTraffic = $options.reports.exchangeMailTraffic
$reportTopMailTraffic = $options.reports.exchangeTopMailTraffic
$reportATPDetections = $options.reports.exchangeATPDetections
if ( $reportMailboxUsageAndProvisioning -or `
$reportOffice365GroupsProvisioning -or `
$reportEmailAppUsage -or `
$reportTopMailTraffic -or `
$reportMailTraffic -or `
$reportATPDetections) {
$enabledReport += "Exchange"
}
# Sharepoint
$reportSPO = $options.reports.sharepoint
if ($reportSPO) { $enabledReport += "SharePoint" }
# Onedrive
$reportOneDrive = $options.reports.onedrive
if ($reportOneDrive) { $enabledReport += "OneDrive" }
# SkypeForBusiness
$reportSkypeForBusiness = $options.reports.SkypeForBusiness
if ($reportSkypeForBusiness) { $enabledReport += "Skype for Business" }
# Teams
$reportTeams = $options.reports.teams
if ($reportTeams) { $enabledReport += "Microsoft Teams" }
# Check if there's any enabled report. If none, stop transcript and exit script.
if (!$enabledReport) {
Write-Output "$(Get-Date) : [X] There are no reports enabled in your configuration file. Make sure to enable reports first then try again."
LogEnd
return $null
}
$enabledReportList = $enabledReport -join ","
Write-Output "$(Get-Date) : Enabled reports are - $enabledReportList"
#endregion
# Start Transcript Logging
if ($transLog) {
Write-Output "$(Get-Date) : Transcript - $($logFile)"
LogStart -logPath $logFile
}
Write-Output "$(Get-Date) : Script Start"
#Region MS Grap Authentication
# tenantName check
$tenantName = $options.auth.tenantName
if (!($tenantName)) {
Write-Output "$(Get-Date) : [X] The tenantName value is missing from the configuration file $Config"
LogEnd
return $null
}
# msGraphAppKey check
$msGraphAppID = $options.auth.msGraphAppID
if (!($msGraphAppID)) {
Write-Output "$(Get-Date) : [X] The msGraphAppID value is missing from the configuration file $Config"
LogEnd
return $null
}
# if msGraphAuthType = 1 (Certificate)
if ($options.auth.msGraphAuthType -eq 1) {
$msGraphAppCertificateThumbprint = $options.auth.msGraphAppCertificateThumbprint
if (!($msGraphAppCertificateThumbprint)) {
Write-Output "$(Get-Date) : [X] The msGraphAppCertificateThumbprint is missing from the configuration file $Config."
LogEnd
return $null
}
else {
try {
Write-Output "$(Get-Date) : Trying to acquire an access token using certificate [$msGraphAppCertificateThumbprint]."
$oAuth = Get-MsalToken -ClientId $msGraphAppID -TenantId $tenantName -ClientCertificate (Get-Item Cert:\CurrentUser\My\$msGraphAppCertificateThumbprint) -ErrorAction STOP
$headerParams = @{'Authorization' = "Bearer $($oAuth.AccessToken)" }
Write-Output "$(Get-Date) : [$([Char]8730)] Graph Graph API access token acquired."
}
catch {
Write-Output "$(Get-Date) : [X] Failed to get access token."
Write-Output "$(Get-Date) : $($_.Exception.Message)"
LogEnd
return $null
}
}
}
# if msGraphAuthType = 2 (App Key)
if ($options.auth.msGraphAuthType -eq 2) {
# if msGraphAppKey is missing
$msGraphAppKey = $options.auth.msGraphAppKey
if (!($msGraphAppKey)) {
Write-Output "$(Get-Date) : [X] The msGraphAppKey is missing from the configuration file $Config."
LogEnd
return $null
}
else {
try {
Write-Output "$(Get-Date) : Trying to acquire an access token using app key."
$msGraphAppKeySecured = New-Object securestring
$msGraphAppKey.ToCharArray() | ForEach-Object { $msGraphAppKeySecured.AppendChar($_) }
$oAuth = Get-MsalToken -ClientId $msGraphAppID -TenantId $tenantName -ClientSecret $msGraphAppKeySecured -ErrorAction STOP
$headerParams = @{'Authorization' = "Bearer $($oAuth.AccessToken)" }
Write-Output "$(Get-Date) : [$([Char]8730)] Graph Graph API access token acquired."
}
catch {
Write-Output "$(Get-Date) : [X] Failed to get access token."
Write-Output "$(Get-Date) : $($_.Exception.Message)"
LogEnd
return $null
}
}
}
#EndRegion
#Region Exchange Authentication
if ($enabledReport -contains 'Exchange') {
$exchangeAuthType = $options.auth.exchangeAuthType
if ($exchangeAuthType) {
if ($exchangeAuthType -eq 1) {
$exchangeAppID = $options.auth.exchangeAppID
$exchangeAppCertificateThumbprint = $options.auth.exchangeAppCertificateThumbprint
if (!($exchangeAppID) -or !($exchangeAppCertificateThumbprint)) {
Write-Output "$(Get-Date) : [X] The exchangeAppID or exchangeAppCertificateThumbprint values is missing from the configuration file $Config."
LogEnd
return $null
}
else {
try {
Write-Output "$(Get-Date) : Trying to connect Exchange Online PowerShell using app certificate [$exchangeAppCertificateThumbprint]."
Connect-ExchangeOnline -AppId $exchangeAppID -Organization $tenantName -CertificateThumbprint $exchangeAppCertificateThumbprint -ShowBanner:$false -ErrorAction STOP
Write-Output "$(Get-Date) : [$([Char]8730)] Connected to Exchange Online PowerShell."
}
catch {
Write-Output "$(Get-Date) : [X] Failed to connect to Exchange Online PowerShell. [X]"
Write-Output "$(Get-Date) : $($_.Exception.Message)"
LogEnd
return $null
}
}
}
elseif ($exchangeAuthType -eq 2) {
$exchangeCredentialFile = $options.auth.exchangeCredentialFile
if (!($exchangeCredentialFile)) {
Write-Output "$(Get-Date) : [X] The exchangeCredentialFile value is missing from the configuration file $Config.`nUpdate your configuration to point exchangeCredentialFile to the right location of the credential file."
LogEnd
return $null
}
else {
try {
$exchangeCredential = Import-Clixml $exchangeCredentialFile -ErrorAction STOP
Write-Output "$(Get-Date) : Trying to connect Exchange Online PowerShell using credential."
Connect-ExchangeOnline -Organization $tenantName -Credential $exchangeCredential -ShowBanner:$false -ErrorAction STOP
Write-Output "$(Get-Date) : [$([Char]8730)] Connected to Exchange Online PowerShell."
}
catch {
Write-Output "$(Get-Date) : [X] Failed to connect to Exchange Online PowerShell."
Write-Output "$(Get-Date) : $($_.Exception.Message)"
LogEnd
return $null
}
}
}
elseif ($exchangeAuthType -eq 3) {
$exchangeAppID = $options.auth.exchangeAppID
}
else {
Write-Output "$(Get-Date) : [X] The exchangeAuthType value is not valid.`nValid values as 1, 2.`n * 1 = App + Certificate`n2 = Credential"
LogEnd
return $null
}
}
else {
Write-Output "$(Get-Date) : [X] The exchangeAuthType value is not valid.`nValid values as 1, 2.`n * 1 = App + Certificate`n2 = Credential"
LogEnd
return $null
}
}
#EndRegion
#organization details
$uri = "https://graph.microsoft.com/beta/organization`?`$select=displayname"
$organizationName = (Invoke-RestMethod -Method Get -Uri $uri -Headers $headerParams).Value.displayname
Write-Output "$(Get-Date) : Your organization name is $organizationName"
# Set report period
[int]$dPeriod = $options.parameters.period
[datetime]$today = (Get-Date).Date
$startDate = ($today).AddDays(-$dPeriod)
$endDate = $today
Write-Output "$(Get-Date) : Setting Report Period to $dPeriod Days [$($startDate)] - [$($endDate)]"
$fileSuffix = ('{0:yyyy-MMM-dd_}' -f ($startDate)) + ('{0:yyyy-MMM-dd}' -f ($endDate))
# Create report folder for this period (if it does not exist)
$reportFolder = "$($script_root)\reports\$($organizationName)\$fileSuffix"
if (!(Test-Path $reportFolder)) {
Write-Output "$(Get-Date) : Creating Reports folder $($reportFolder)"
New-Item -ItemType Directory -Path $reportFolder | Out-Null
}
# Empty the report folder
Get-ChildItem -Path "$($reportFolder)\*" -Exclude debug.log | Remove-Item -Force
# HTML report header
$mailSubject = "[$($organizationName)] Microsoft 365 Usage Report for the period of " + ("{0:yyyy-MM-dd}" -f $startDate ) + " to " + ("{0:yyyy-MM-dd}" -f $endDate)
$html = '<html><head><title>' + $($mailSubject) + '</title>'
$html += '<style type="text/css">'
$html += (Get-Content $styleFolder\style.css -Raw)
$html += '</style>'
$html += '</head><body>'
$html += '<table id="mainTable">'
if ($showLogo) {
$html += '<tr><td class="placeholder"><img src="' + $logoFile + '"></td>'
}
$html += '<td class="vl"></td>'
$html += '<td class="title">' + $organizationName + '<br>' + 'Microsoft 365 Usage Report' + '<br>' + ("{0:MMMM dd, yyyy}" -f $startDate ) + " to " + ("{0:MMMM dd, yyyy}" -f $endDate) + '</td></tr>'
$html += '<tr><td class="placeholder" colspan="3"></td></tr>'
$html += '</table>'
#==============================================
# Licenses Assigned Report
#==============================================
if ($reportLicenseAssigned) {
Write-Output "$(Get-Date) : Processing Assigned License Report"
Write-Output "$(Get-Date) : --> Getting Office 365 user count and assigned licenses"
$uri = "https://graph.microsoft.com/$graphApiVersion/reports/getOffice365ActiveUserDetail(period='D$($dPeriod)')"
$raw = (Invoke-RestMethod -Method Get -Uri $uri -Headers $headerParams) | ConvertFrom-Csv
$license = "" | Select-Object TotalUsers, TotalUsersLicensed, TotalUsersUnlicensed, Exchange, Sharepoint, OneDrive, SkypeForBusiness, Yammer, Teams
$license.TotalUsers = $raw.Count
$license.TotalUsersLicensed = ($raw | Where-Object { $_."Assigned Products" }).count
$license.TotalUsersUnlicensed = ($raw | Where-Object { !($_."Assigned Products") }).count
$license.Exchange = ($raw | Where-Object { $_."Has Exchange License" -eq $true }).count
$license.Sharepoint = ($raw | Where-Object { $_."Has Sharepoint License" -eq $true }).count
$license.OneDrive = ($raw | Where-Object { $_."Has OneDrive License" -eq $true }).count
$license.SkypeForBusiness = ($raw | Where-Object { $_."Has Skype For Business License" -eq $true }).count
$license.Yammer = ($raw | Where-Object { $_."Has Yammer License" -eq $true }).count
$license.Teams = ($raw | Where-Object { $_."Has Teams License" -eq $true }).count
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $officeIconFile + '"></th><th class="section">Users and Assigned Licenses</th></tr></table><table id="mainTable">'
$html += '<tr><th>Total Users</th><td>' + ("{0:N0}" -f $license.TotalUsers) + '</td></tr>'
$html += '<tr><th>Licensed Users</th><td>' + ("{0:N0}" -f $license.TotalUsersLicensed) + '</td></tr>'
$html += '<tr><th>Unlicensed Users</th><td>' + ("{0:N0}" -f $license.TotalUsersUnlicensed) + '</td></tr>'
$html += '<tr><th>Exchange</th><td>' + ("{0:N0}" -f $license.Exchange) + '</td></tr>'
$html += '<tr><th>Sharepoint</th><td>' + ("{0:N0}" -f $license.Sharepoint) + '</td></tr>'
$html += '<tr><th>OneDrive</th><td>' + ("{0:N0}" -f $license.OneDrive) + '</td></tr>'
$html += '<tr><th>Skype for Business</th><td>' + ("{0:N0}" -f $license.SkypeForBusiness) + '</td></tr>'
$html += '<tr><th>Yammer</th><td>' + ("{0:N0}" -f $license.Yammer) + '</td></tr>'
$html += '<tr><th>Teams</th><td>' + ("{0:N0}" -f $license.Teams) + '</td></tr>'
$html += '<tr><td class="placeholder"> </td></tr>'
$html += '</table>'
if ($saveRawData) {
$raw | Export-Csv "$($reportFolder)\raw_Office365ActiveUserDetail.csv" -NoTypeInformation
}
}
#==============================================
# MS365 Active Users Count Report
#==============================================
if ($reportMs365ActiveUsers) {
Write-Output "$(Get-Date) : Processing Office 365 Active Users Report"
Write-Output "$(Get-Date) : --> Getting Office 365 active user count per service"
$uri = "https://graph.microsoft.com/$graphApiVersion/reports/getOffice365ServicesUserCounts(period='D$($dPeriod)')"
$result = (Invoke-RestMethod -Method Get -Uri $uri -Headers $headerParams) | ConvertFrom-Csv
$raw = "" | Select-Object Office365Active, ExchangeActive, OneDriveActive, SharePointActive, SkypeforBusinessActive, YammerActive, TeamsActive, Office365inActive, ExchangeinActive, OneDriveinActive, SharePointinActive, SkypeforBusinessinActive, YammerinActive, TeamsinActive
$raw.Office365Active = $result."office 365 active"
$raw.ExchangeActive = $result."exchange Active"
$raw.OneDriveActive = $result."oneDrive Active"
$raw.SharePointActive = $result."sharePoint Active"
$raw.SkypeforBusinessActive = $result."skype For Business Active"
$raw.YammerActive = $result."yammer Active"
$raw.TeamsActive = $result."teams Active"
$raw.Office365inActive = $result."office 365 inactive"
$raw.ExchangeinActive = $result."exchange inActive"
$raw.OneDriveinActive = $result."oneDrive inActive"
$raw.SharePointinActive = $result."sharePoint inActive"
$raw.SkypeforBusinessinActive = $result."skype For Business inActive"
$raw.YammerinActive = $result."yammer inActive"
$raw.TeamsinActive = $result."teams inActive"
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $officeIconFile + '"></th><th class="section">Active Users</th></tr></table><table id="mainTable">'
$html += '<tr><th>Service</th><th>Active</th><th>Inactive</th></tr>'
$html += '<tr><th>Office 365</th><td>' + ("{0:N0}" -f [int]$raw.Office365Active) + '</td><td>' + ("{0:N0}" -f [int]$raw.Office365inActive) + '</td></tr>'
$html += '<tr><th>Exchange</th><td>' + ("{0:N0}" -f [int]$raw.ExchangeActive) + '</td><td>' + ("{0:N0}" -f [int]$raw.ExchangeinActive) + '</td></tr>'
$html += '<tr><th>OneDrive</th><td>' + ("{0:N0}" -f [int]$raw.OneDriveActive) + '</td><td>' + ("{0:N0}" -f [int]$raw.OneDriveinActive) + '</td></tr>'
$html += '<tr><th>Sharepoint</th><td>' + ("{0:N0}" -f [int]$raw.SharepointActive) + '</td><td>' + ("{0:N0}" -f [int]$raw.SharepointinActive) + '</td></tr>'
$html += '<tr><th>Skype for Business</th><td>' + ("{0:N0}" -f [int]$raw.SkypeForBusinessActive) + '</td><td>' + ("{0:N0}" -f $raw.SkypeForBusinessinActive) + '</td></tr>'
$html += '<tr><th>Yammer</th><td>' + ("{0:N0}" -f [int]$raw.YammerActive) + '</td><td>' + ("{0:N0}" -f [int]$raw.YammerinActive) + '</td></tr>'
$html += '<tr><th>Teams</th><td>' + ("{0:N0}" -f [int]$raw.TeamsActive) + '</td><td>' + ("{0:N0}" -f [int]$raw.TeamsinActive) + '</td></tr>'
$html += '<tr><td class="placeholder"> </td></tr>'
$html += '</table>'
if ($saveRawData) {
$raw | Export-Csv "$($reportFolder)\raw_Office365ServicesUserCounts.csv" -NoTypeInformation
}
}
#==============================================
# MS365 Activations Users Count Report
#==============================================
if ($reportMs365ActivationUsers) {
Write-Output "$(Get-Date) : Processing Office 365 Activations Users Count Report"
Write-Output "$(Get-Date) : --> Getting Office 365 app activations count"
$uri = "https://graph.microsoft.com/$graphApiVersion/reports/getOffice365ActivationsUserCounts"
$result = (Invoke-RestMethod -Method Get -Uri $uri -Headers $headerParams) | ConvertFrom-Csv
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $officeIconFile + '"></th><th class="section">Product Activations</th></tr></table><table id="mainTable">'
$html += '<tr><th>Product Type</th><th>Assigned</th><th>Activated</th><th>Shared Computer Activation</th></tr>'
foreach ($detail in $result) {
$html += '<tr><th>' + ($detail."product Type") + '</th>
<td>' + ("{0:N0}" -f [int]$detail.assigned) + '</td>
<td>' + ("{0:N0}" -f [int]$detail.activated) + '</td>
<td>' + ("{0:N0}" -f [int]$detail."shared Computer Activation") + '</td>
</tr>'
}
$html += '<tr><td class="placeholder"> </td></tr></table>'
if ($saveRawData) {
$result | Export-Csv "$($reportFolder)\raw_Office365ActivationsUserCounts.csv" -NoTypeInformation
}
}
#==============================================
# Exchange Online Report
#==============================================
if ($reportMailboxUsageAndProvisioning) {
#get mailbox usage
Write-Output "$(Get-Date) : Processing Mailbox Usage and Provisioning Report"
Write-Output "$(Get-Date) : --> Getting Exchange Online mailbox usage and provisioning details"
$uri = "https://graph.microsoft.com/$graphApiVersion/reports/getMailboxUsageDetail(period='D$($dPeriod)')"
$result = (Invoke-RestMethod -Method Get -Uri $uri -Headers $headerParams) | ConvertFrom-Csv
$mailboxUsageAndProvisioningData = @()
foreach ($detail in $result) {
$raw = "" | Select-Object UserPrincipalName, DisplayName, IsDeleted, DeletedDate, CreatedDate, LastActivityDate, StorageUsedByte, IssueWarningQuotaByte, ProhibitSendQuotaByte, ProhibitSendReceiveQuotaByte, IsBelow25Percent, IsOverQuota, IsInActive
$raw.UserPrincipalName = $detail."User Principal Name"
$raw.DisplayName = $detail."Display Name"
$raw.IsDeleted = $detail."Is Deleted"
if ($detail."Deleted Date") { $raw.DeletedDate = [datetime]$detail."Deleted Date" }
if ($detail."Created Date") { $raw.CreatedDate = [datetime]$detail."Created Date" }
if ($detail."Last Activity Date") { $raw.LastActivityDate = [datetime]$detail."Last Activity Date" }
$raw.StorageUsedByte = [double]$detail."Storage Used (Byte)"
$raw.IssueWarningQuotaByte = [double]$detail."Issue Warning Quota (Byte)"
$raw.ProhibitSendQuotaByte = [double]$detail."Prohibit Send Quota (Byte)"
$raw.ProhibitSendReceiveQuotaByte = [double]$detail."Prohibit Send/Receive Quota (Byte)"
if (!($raw.LastActivityDate)) {
$raw.IsInActive = $true
}
elseif ($raw.LastActivityDate -lt $startDate) {
$raw.IsInActive = $true
}
else {
$raw.IsInActive = $false
}
if ((($raw.StorageUsedByte / $raw.ProhibitSendReceiveQuotaByte) * 100) -lt 25) {
$raw.IsBelow25Percent = $true
}
else {
$raw.IsBelow25Percent = $false
}
if ($raw.StorageUsedByte -ge $raw.ProhibitSendReceiveQuotaByte) {
$raw.IsOverQuota = $true
}
else {
$raw.IsOverQuota = $false
}
$mailboxUsageAndProvisioningData += $raw
}
# Get deleted mailbox
Write-Output "$(Get-Date) : --> Getting list of deleted mailboxes"
# v1.2.1 - changed back to Get-Mailbox
$deletedMailbox = @(Get-Mailbox -ResultSize Unlimited -SoftDeletedMailbox -Filter "WhenSoftDeleted -ge '$startDate'" |
Select-Object UserPrincipalName, WhenSoftDeleted |
Sort-Object UserPrincipalName)
$exchangeMailboxStatus = "" | Select-Object ActiveMailbox, InActiveMailbox, CreatedMailbox, DeletedMailbox
$exchangeMailboxStatus.ActiveMailbox = ($mailboxUsageAndProvisioningData | Where-Object { $_.IsInActive -eq $false }).count
$exchangeMailboxStatus.InactiveMailbox = ($mailboxUsageAndProvisioningData | Where-Object { $_.IsInActive }).count
$exchangeMailboxStatus.CreatedMailbox = ($mailboxUsageAndProvisioningData | Where-Object { $_.CreatedDate -ge $today.AddDays(-$dPeriod) }).count
$exchangeMailboxStatus.DeletedMailbox = $deletedMailbox.count
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $exchangeIconFile + '"></th><th class="section">Mailbox Status</th></tr></table><table id="mainTable">'
$html += '<tr><th>Active Mailbox</th><td>' + ("{0:N0}" -f $exchangeMailboxStatus.ActiveMailbox) + '</td></tr>'
$html += '<tr><th>Inactive Mailbox</th><td>' + ("{0:N0}" -f $exchangeMailboxStatus.InactiveMailbox) + '</td></tr>'
$html += '</table>'
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $exchangeIconFile + '"></th><th class="section">Mailbox Provisioning</th></tr></table><table id="mainTable">'
$html += '<tr><th>Created Mailbox</th><td>' + ("{0:N0}" -f $exchangeMailboxStatus.CreatedMailbox) + '</td></tr>'
$html += '<tr><th>Deleted Mailbox</th><td>' + ("{0:N0}" -f $exchangeMailboxStatus.deletedMailbox) + '</td></tr>'
$html += '<tr><td class="placeholder"> </td></tr></table>'
if ($saveRawData) {
$result | Export-Csv "$($reportFolder)\raw_getMailboxUsageDetail.csv" -NoTypeInformation
$mailboxUsageAndProvisioningData | Export-Csv "$($reportFolder)\raw_MailboxUsageDetail.csv" -NoTypeInformation
$deletedMailbox | Export-Csv "$($reportFolder)\raw_exchangeDeletedMailbox.csv" -NoTypeInformation
}
# Get quota status
Write-Output "$(Get-Date) : Processing Mailbox Quota Report"
Write-Output "$(Get-Date) : --> Getting Exchange Online mailbox quota status"
$uri = "https://graph.microsoft.com/$graphApiVersion/reports/getMailboxUsageQuotaStatusMailboxCounts(period='D$($dPeriod)')"
$raw = ((Invoke-RestMethod -Method Get -Uri $uri -Headers $headerParams) | ConvertFrom-Csv)[0]
$quota = "" | Select-Object UnderLimit, WarningIssued, SendProhibited, SendReceiveProhibited, Below25Percent
[int]$quota.UnderLimit = $raw."Under Limit"
[int]$quota.WarningIssued = $raw."Warning Issued"
[int]$quota.SendProhibited = $raw."Send Prohibited"
[int]$quota.SendReceiveProhibited = $raw."Send/Receive Prohibited"
[int]$quota.Below25Percent = ($mailboxUsageAndProvisioningData | Where-Object { $_.IsBelow25Percent }).count
# EXO Storage Used
Write-Output "$(Get-Date) : --> Getting Exchange Online storage usage (tenant)"
$uri = "https://graph.microsoft.com/$graphApiVersion/reports/getMailboxUsageStorage(period='D$($dPeriod)')"
$exoStorage = ((Invoke-RestMethod -Method Get -Uri $uri -Headers $headerParams) | ConvertFrom-Csv)
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $exchangeIconFile + '"></th><th class="section">Mailbox Storage</th></tr></table><table id="mainTable">'
$html += '<tr><th>Storage Used (TB)</th><td>' + ("{0:N2}" -f (($exoStorage[0].'Storage Used (Byte)') / 1TB)) + '</td></tr>'
$html += '<tr><th>Below 25% Used</th><td>' + ("{0:N0}" -f $quota.Below25Percent) + '</td></tr>'
$html += '<tr><th>Under Limit</th><td>' + ("{0:N0}" -f $quota.underLimit) + '</td></tr>'
$html += '<tr><th>Warning Issued</th><td>' + ("{0:N0}" -f $quota.WarningIssued) + '</td></tr>'
$html += '<tr><th>Send Prohibited</th><td>' + ("{0:N0}" -f $quota.SendProhibited) + '</td></tr>'
$html += '<tr><th>Send/Receive Prohibited</th><td>' + ("{0:N0}" -f $quota.SendReceiveProhibited) + '</td></tr>'
$html += '<tr><td class="placeholder"> </td></tr></table>'
if ($saveRawData) {
$raw | Export-Csv "$($reportFolder)\raw_MailboxUsageQuotaStatusMailboxCounts.csv" -NoTypeInformation
}
}
# Email app report
if ($reportEmailAppUsage) {
Write-Output "$(Get-Date) : Processing Email App Report"
Write-Output "$(Get-Date) : --> Getting Exchange Online email app distribution count"
$uri = "https://graph.microsoft.com/$graphApiVersion/reports/getEmailAppUsageAppsUserCounts(period='D$($dPeriod)')"
$raw = (Invoke-RestMethod -Method Get -Uri $uri -Headers $headerParams) | ConvertFrom-Csv
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $exchangeIconFile + '"></th><th class="section">Email Apps Usage</th></tr></table><table id="mainTable">'
$html += '<tr><th>Mail for Mac</th><td>' + ("{0:N0}" -f [int]$raw."Mail for Mac") + '</td></tr>'
$html += '<tr><th>Outlook for Mac</th><td>' + ("{0:N0}" -f [int]$raw."Outlook for Mac") + '</td></tr>'
$html += '<tr><th>Outlook for Windows</th><td>' + ("{0:N0}" -f [int]$raw."Outlook for Windows") + '</td></tr>'
$html += '<tr><th>Outlook for Mobile</th><td>' + ("{0:N0}" -f [int]$raw."Outlook for Mobile") + '</td></tr>'
$html += '<tr><th>Other for Mobile</th><td>' + ("{0:N0}" -f [int]$raw."Other for Mobile") + '</td></tr>'
$html += '<tr><th>Outlook for Web</th><td>' + ("{0:N0}" -f [int]$raw."Outlook for Web") + '</td></tr>'
$html += '<tr><th>POP3 App</th><td>' + ("{0:N0}" -f [int]$raw."POP3 App") + '</td></tr>'
$html += '<tr><th>IMAP4 App</th><td>' + ("{0:N0}" -f [int]$raw."IMAP4 App") + '</td></tr>'
$html += '<tr><th>SMTP App</th><td>' + ("{0:N0}" -f [int]$raw."SMTP App") + '</td></tr>'
$html += '<tr><td class="placeholder"> </td></tr></table>'
if ($saveRawData) {
$raw | Export-Csv "$($reportFolder)\raw_exchangeMailAppUsage.csv" -NoTypeInformation
}
}
# Microsoft 365 Groups report
if ($reportOffice365GroupsProvisioning) {
Write-Output "$(Get-Date) : Processing Office 365 Groups Report"
# Get all current Microsoft 365 Groups only
Write-Output "$(Get-Date) : --> Getting all Office 365 groups"
$liveGroups = @()
$uri = "https://graph.microsoft.com/$graphApiVersion/groups`?`$filter=groupTypes/any(c:c+eq+'Unified')`&`$select=mailNickname,deletedDateTime,createdDateTime"
$raw = (Invoke-RestMethod -Method Get -Uri $uri -Headers $headerParams)
if ($raw.value) {
$liveGroups += $raw.value
while (($raw.'@odata.nextLink')) {
$raw = (Invoke-RestMethod -Method Get -Uri ($raw.'@odata.nextLink') -Headers $headerParams)
$liveGroups += $raw.value
}
}
Write-Output "$(Get-Date) : --> Getting list of deleted Office 365 groups"
# Get all deleted Microsoft 365 Groups only
$deletedGroups = @()
$uri = "https://graph.microsoft.com/$graphApiVersion/directory/deletedItems/microsoft.graph.group`?`$filter=groupTypes/any(c:c+eq+'Unified')`&`$select=mailNickname,deletedDateTime,createdDateTime"
$raw = (Invoke-RestMethod -Method Get -Uri $uri -Headers $headerParams)
if ($raw.value) {
$deletedGroups += $raw.value
while (($raw.'@odata.nextLink')) {
$raw = (Invoke-RestMethod -Method Get -Uri ($raw.'@odata.nextLink') -Headers $headerParams)
$deletedGroups += $raw.value
}
}
$o365Groups = "" | Select-Object LiveGroups, CreatedGroups, DeletedGroups
[int]$o365Groups.LiveGroups = $liveGroups.count
[int]$o365Groups.CreatedGroups = ($liveGroups | Where-Object { ([datetime]$_.createdDateTime) -ge $startDate }).Count
[int]$o365Groups.DeletedGroups = ($deletedGroups | Where-Object { ([datetime]$_.deletedDateTime) -ge $startDate }).Count
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $exchangeIconFile + '"></th><th class="section">Microsoft 365 Groups</th></tr></table><table id="mainTable">'
$html += '<tr><th>Current Groups</th><td>' + ("{0:N0}" -f $o365Groups.LiveGroups) + '</td></tr>'
$html += '<tr><th>Created Groups</th><td>' + ("{0:N0}" -f $o365Groups.CreatedGroups) + '</td></tr>'
$html += '<tr><th>Deleted Groups</th><td>' + ("{0:N0}" -f $o365Groups.DeletedGroups) + '</td></tr>'
$html += '<tr><td class="placeholder"> </td></tr></table>'
if ($saveRawData) {
$liveGroups | Export-Csv "$($reportFolder)\raw_exchangeOffice365LiveGroups.csv" -NoTypeInformation
$deletedGroups | Export-Csv "$($reportFolder)\raw_exchangeOffice365DeletedGroups.csv" -NoTypeInformation -Append
}
}
# Mail traffic (inbound/outbound)
if ($reportMailTraffic) {
Write-Output "$(Get-Date) : Processing Mail Traffic Report"
Write-Output "$(Get-Date) : --> Getting mail traffic data"
<#
v1.2.3
* Fixed inbound count. All inbound messages are now counted.
* Fixed outbound count. All outbound messages are now counted.
* Fixed spam count count. All inbound and outbound spam are now counted.
* Fixed malware count count. All inbound and outbound spam are now counted.
#>
<#
v1.2.8
* Since Microsoft removed the Get-MailTrafficReport cmdlet, replacing it with Get-MailFlowStatusReport
#>
$mailTrafficData = Get-MailFlowStatusReport -StartDate $startDate.ToUniversalTime() -EndDate $endDate.ToUniversalTime() -Direction Inbound, Outbound
[int]$totalMessageCount = ($mailTrafficData | Measure-Object MessageCount -Sum).Sum
[int]$inboundMessageCount = ($mailTrafficData | Where-Object { $_.Direction -eq "Inbound" } | Measure-Object MessageCount -Sum).Sum
[int]$outboundMessageCount = ($mailTrafficData | Where-Object { $_.Direction -eq "Outbound" } | Measure-Object MessageCount -Sum).Sum
[int]$edgeProtectionMessageCount = ($mailTrafficData | Where-Object { $_.EventType -eq "EdgeBlockSpam" } | Measure-Object MessageCount -Sum).Sum
[int]$malwareMessageCount = ($mailTrafficData | Where-Object { $_.EventType -eq "EmailMalware" } | Measure-Object MessageCount -Sum).Sum
[int]$spamMessageCount = ($mailTrafficData | Where-Object { $_.EventType -eq "SpamDetections" } | Measure-Object MessageCount -Sum).Sum
[int]$phishMessageCount = ($mailTrafficData | Where-Object { $_.EventType -eq "EmailPhish" } | Measure-Object MessageCount -Sum).Sum
[int]$goodMessageCount = ($mailTrafficData | Where-Object { $_.EventType -eq "GoodMail" } | Measure-Object MessageCount -Sum).Sum
[int]$ruleMessageCount = ($mailTrafficData | Where-Object { $_.EventType -eq "TransportRules" } | Measure-Object MessageCount -Sum).Sum
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $exchangeIconFile + '"></th><th class="section">Mail Traffic Summary</th></tr></table><table id="mainTable">'
$html += '<tr><th>Total Email</th><td>' + ("{0:N0}" -f $totalMessageCount) + '</td></tr>'
$html += '<tr><th>Outbound Email</th><td>' + ("{0:N0}" -f $inboundMessageCount) + '</td></tr>'
$html += '<tr><th>InboundEmail </th><td>' + ("{0:N0}" -f $outboundMessageCount) + '</td></tr>'
$html += '<tr><th>Good Email</th><td>' + ("{0:N0}" -f $goodMessageCount) + '</td></tr>'
$html += '<tr><th>Edge Block</th><td>' + ("{0:N0}" -f $edgeProtectionMessageCount) + '</td></tr>'
$html += '<tr><th>Malware</th><td>' + ("{0:N0}" -f $malwareMessageCount) + '</td></tr>'
$html += '<tr><th>Spam</th><td>' + ("{0:N0}" -f $spamMessageCount) + '</td></tr>'
$html += '<tr><th>Phising</th><td>' + ("{0:N0}" -f $phishMessageCount) + '</td></tr>'
$html += '<tr><th>Transport Rule</th><td>' + ("{0:N0}" -f $ruleMessageCount) + '</td></tr>'
$html += '<tr><td class="placeholder"> </td></tr></table>'
if ($saveRawData) {
$mailTrafficData | Export-Csv "$($reportFolder)\raw_exchangeMailTraffic.csv" -NoTypeInformation
}
}
# ATP Mail detections
if ($reportATPDetections) {
<#
v1.2.3 - Replaced Get-MailTrafficATPReport with Get-ATPTotalTrafficReport.
#>
Write-Output "$(Get-Date) : Processing ATP Mail Detection Report"
$atpTrafficReport = Get-ATPTotalTrafficReport -StartDate $startDate -EndDate ($endDate).AddDays(-1) -AggregateBy Summary | Select-Object EventType, MessageCount
Write-Output "$(Get-Date) : --> Getting ATP SafeLinks blocked message count"
$atpSafeLinks = $atpTrafficReport | Where-Object { $_.EventType -eq 'TotalSafeLinkCount' }
Write-Output "$(Get-Date) : --> Getting ATP SafeAttachments blocked message count"
$atpSafeAttachments = $atpTrafficReport | Where-Object { $_.EventType -eq 'TotalSafeAttachmentCount' }
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $defenderIconFile + '"></th><th class="section">ATP Email Detection</th></tr></table><table id="mainTable">'
$html += '<tr><th>Blocked by ATP Safe Links</th><td>' + ("{0:N0}" -f [int]$atpSafeLinks.MessageCount) + '</td></tr>'
$html += '<tr><th>Blocked by ATP Safe Attachments</th><td>' + ("{0:N0}" -f [int]$atpSafeAttachments.MessageCount) + '</td></tr>'
$html += '<tr><td class="placeholder"> </td></tr></table>'
if ($saveRawData) {
$atpTrafficReport | Export-Csv "$($reportFolder)\raw_exchangeAtpTrafficReport.csv" -NoTypeInformation
}
}
# Top 10 mail traffic reports
<#
v1.2.3
* Replace Get-MailTrafficTopReport wit MailTrafficSummaryReport
#>
if ($reportTopMailTraffic) {
Write-Output "$(Get-Date) : Processing Top Mail Traffic Report"
# Top 10 Spam Recipients
Write-Output "$(Get-Date) : --> Getting Top 10 Spam Recipients"
$top10SpamRecipient = Get-MailTrafficSummaryReport -StartDate $startDate -EndDate $endDate -Category TopSpamRecipient | Select-Object -First 10 -Property C1, C2
# Top 10 Malware Recipients
Write-Output "$(Get-Date) : --> Getting Top 10 Malware Recipients"
$top10MalwareRecipient = Get-MailTrafficSummaryReport -StartDate $startDate -EndDate $endDate -Category TopMalwareRecipient | Select-Object -First 10 -Property C1, C2
# Top 10 Mail Senders
Write-Output "$(Get-Date) : --> Getting Top 10 Mail Senders"
$top10MailSender = Get-MailTrafficSummaryReport -StartDate $startDate -EndDate $endDate -Category TopMailSender | Select-Object -First 10 -Property C1, C2
# Top 10 Mail Recipients
Write-Output "$(Get-Date) : --> Getting Top 10 Mail Recipients"
$top10MailRecipient = Get-MailTrafficSummaryReport -StartDate $startDate -EndDate $endDate -Category TopMailRecipient | Select-Object -First 10 -Property C1, C2
# Top 10 Malware
Write-Output "$(Get-Date) : --> Getting Top 10 Malware"
$top10Malware = Get-MailTrafficSummaryReport -StartDate $startDate -EndDate $endDate -Category TopMalware | Select-Object -First 10 -Property C1, C2
# Top 10 mail sender
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $exchangeIconFile + '"></th><th class="section">Top 10 Email Sender</th></tr></table><table id="mainTable">'
$html += '<tr><th>User</th><th>Message Count</th></tr>'
foreach ($mailSender in $top10MailSender) {
$html += '<tr><td>' + $mailSender.C1 + '</td><td>' + ("{0:N0}" -f [int]$mailSender.C2) + '</td></tr>'
}
$html += '<tr><td class="placeholder"> </td></tr></table>'
# Top 10 mail recipients
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $exchangeIconFile + '"></th><th class="section">Top 10 Email Recipients</th></tr></table><table id="mainTable">'
$html += '<tr><th>User</th><th>Message Count</th></tr>'
foreach ($mailRecipient in $top10MailRecipient) {
$html += '<tr><td>' + $mailRecipient.C1 + '</td><td>' + ("{0:N0}" -f [int]$mailRecipient.C2) + '</td></tr>'
}
$html += '<tr><td class="placeholder"> </td></tr></table>'
# Top 10 Spam Recipients
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $exchangeIconFile + '"></th><th class="section">Top 10 Spam Recipients</th></tr></table><table id="mainTable">'
$html += '<tr><th>User</th><th>Message Count</th></tr>'
foreach ($spamRecipient in $top10SpamRecipient) {
$html += '<tr><td>' + $spamRecipient.C1 + '</td><td>' + ("{0:N0}" -f [int]$spamRecipient.C2) + '</td></tr>'
}
$html += '<tr><td class="placeholder"> </td></tr></table>'
# Top 10 Malware Recipients
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $exchangeIconFile + '"></th><th class="section">Top 10 Malware Recipients</th></tr></table><table id="mainTable">'
$html += '<tr><th>User</th><th>Message Count</th></tr>'
foreach ($malwareRecipient in $top10MalwareRecipient) {
$html += '<tr><td>' + $malwareRecipient.C1 + '</td><td>' + ("{0:N0}" -f [int]$malwareRecipient.C2) + '</td></tr>'
}
$html += '<tr><td class="placeholder"> </td></tr></table>'
# Top 10 Malware
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $exchangeIconFile + '"></th><th class="section">Top 10 Malware</th></tr></table><table id="mainTable">'
$html += '<tr><th>User</th><th>Message Count</th></tr>'
foreach ($malware in $top10Malware) {
$html += '<tr><td>' + $malware.C1 + '</td><td>' + ("{0:N0}" -f [int]$malware.C2) + '</td></tr>'
}
$html += '<tr><td class="placeholder"> </td></tr></table>'
if ($saveRawData) {
$top10SpamRecipient | Export-Csv "$($reportFolder)\raw_top10SpamRecipient.csv" -NoTypeInformation
$top10MalwareRecipient | Export-Csv "$($reportFolder)\raw_top10MalwareRecipient.csv" -NoTypeInformation
$top10MailSender | Export-Csv "$($reportFolder)\raw_top10MailSender.csv" -NoTypeInformation
$top10MailRecipient | Export-Csv "$($reportFolder)\raw_top10MailRecipient.csv" -NoTypeInformation
$top10Malware | Export-Csv "$($reportFolder)\raw_top10Malware.csv" -NoTypeInformation
}
}
#==============================================
# Sharepoint Report
#==============================================
if ($reportSPO) {
Write-Output "$(Get-Date) : Processing SharePoint Report"
Write-Output "$(Get-Date) : --> Getting SharePoint Sites Usage"
$uri = "https://graph.microsoft.com/$graphApiVersion/reports/getSharePointSiteUsageDetail(period='D$($dPeriod)')"
$raw = (Invoke-RestMethod -Method Get -Uri $uri -Headers $headerParams) | ConvertFrom-Csv
$raw | Add-Member -MemberType ScriptProperty -Name LastActivityDate -Value { [datetime]$this."Last Activity Date" }
$spoSites = "" | Select-Object Total, Active, Inactive
$spoSites.Total = ($raw | Where-Object { $_.'Is Deleted' -eq $false }).Count
$spoSites.Inactive = ($raw | Where-Object { $_.LastActivityDate -lt ($today.AddDays(-$dPeriod)) -and $_.'Is Deleted' -eq $false }).Count
$spoSites.Active = ($raw | Where-Object { $_.LastActivityDate -ge ($today.AddDays(-$dPeriod)) -and $_.'Is Deleted' -eq $false }).Count
Write-Output "$(Get-Date) : --> Getting SharePoint Storage Usage"
$uri = "https://graph.microsoft.com/$graphApiVersion/reports/getSharePointSiteUsageStorage(period='D$($dPeriod)')"
$spoStorage = (Invoke-RestMethod -Method Get -Uri $uri -Headers $headerParams) | ConvertFrom-Csv
$spoStorage | Add-Member -MemberType ScriptProperty -Name ReportDate -Value { [datetime]$this."Report Date" }
$spoStorage | Add-Member -MemberType ScriptProperty -Name Inactive -Value { [int]$this.Total - [int]$this.Active }
$spoStorage | Add-Member -MemberType ScriptProperty -Name UsedGB -Value { "{0:N2}" -f ($this."Storage Used (Byte)" / 1gb) }
$spoStorage | Add-Member -MemberType ScriptProperty -Name UsedTB -Value { "{0:N2}" -f ($this."Storage Used (Byte)" / 1tb) }
$spoStorage = $spoStorage | Sort-Object ReportDate | Select-Object -Last 1
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $sharepointIconFile + '"></th><th class="section">Sharepoint Sites and Storage</th></tr></table><table id="mainTable">'
$html += '<tr><th>Storage Used (TB)</th><td>' + ("{0:N2}" -f [decimal]$spoStorage.UsedTB) + '</td></tr>'
$html += '<tr><th>Total Sites</th><td>' + ("{0:N0}" -f [int]$spoSites.Total) + '</td></tr>'
$html += '<tr><th>Active Sites</th><td>' + ("{0:N0}" -f [int]$sposites.Active) + '</td></tr>'
$html += '<tr><th>InActive Sites</th><td>' + ("{0:N0}" -f [int]$sposites.inactive) + '</td></tr>'
$html += '<tr><td class="placeholder"> </td></tr></table>'
if ($saveRawData) {
$raw | Export-Csv "$($reportFolder)\raw_sharePointSiteUsageDetail.csv" -NoTypeInformation
}
}
#==============================================
# OneDrive Report
#==============================================
if ($reportOneDrive) {
Write-Output "$(Get-Date) : Processing OneDrive Report"
Write-Output "$(Get-Date) : --> Getting OneDrive Usage"
$uri = "https://graph.microsoft.com/$graphApiVersion/reports/getOneDriveUsageAccountDetail(period='D$($dPeriod)')"
$getOneDriveUsageAccountDetail = (Invoke-RestMethod -Method Get -Uri $uri -Headers $headerParams) | ConvertFrom-Csv
$getOneDriveUsageAccountDetail | Add-Member -MemberType ScriptProperty -Name LastActivityDate -Value { [datetime]$this."Last Activity Date" }
$oneDriveSites = "" | Select-Object Total, Active, Inactive
$oneDriveSites.Total = ($getOneDriveUsageAccountDetail).Count
$oneDriveSites.Inactive = ($getOneDriveUsageAccountDetail | Where-Object { $_.LastActivityDate -lt ($today.AddDays(-$dPeriod)) }).Count
$oneDriveSites.Active = ($getOneDriveUsageAccountDetail | Where-Object { $_.LastActivityDate -ge ($today.AddDays(-$dPeriod)) }).Count
Write-Output "$(Get-Date) : --> Getting OneDrive Storage Usage"
$uri = "https://graph.microsoft.com/$graphApiVersion/reports/getOneDriveUsageStorage(period='D$($dPeriod)')"
$oneDriveStorage = (Invoke-RestMethod -Method Get -Uri $uri -Headers $headerParams) | ConvertFrom-Csv
$oneDriveStorage | Add-Member -MemberType ScriptProperty -Name ReportDate -Value { [datetime]$this."Report Date" }
$oneDriveStorage | Add-Member -MemberType ScriptProperty -Name Inactive -Value { [int]$this.Total - [int]$this.Active }
$oneDriveStorage | Add-Member -MemberType ScriptProperty -Name UsedGB -Value { "{0:N2}" -f ($this."Storage Used (Byte)" / 1gb) }
$oneDriveStorage | Add-Member -MemberType ScriptProperty -Name UsedTB -Value { "{0:N2}" -f ($this."Storage Used (Byte)" / 1tb) }
$oneDriveStorage = $oneDriveStorage | Sort-Object ReportDate | Select-Object -Last 1
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $onedriveIconFile + '"></th><th class="section">OneDrive Sites and Storage</th></tr></table><table id="mainTable">'
$html += '<tr><th>Storage Used (TB)</th><td>' + ("{0:N2}" -f [decimal]$oneDriveStorage.UsedTB) + '</td></tr>'
$html += '<tr><th>Total Sites</th><td>' + ("{0:N0}" -f [int]$oneDriveSites.Total) + '</td></tr>'
$html += '<tr><th>Active Sites</th><td>' + ("{0:N0}" -f [int]$oneDriveSites.Active) + '</td></tr>'
$html += '<tr><th>InActive Sites</th><td>' + ("{0:N0}" -f [int]$oneDriveSites.inactive) + '</td></tr>'
$html += '<tr><td class="placeholder"> </td></tr></table>'
if ($saveRawData) {
$getOneDriveUsageAccountDetail | Export-Csv "$($reportFolder)\raw_oneDriveUsageAccountDetail.csv" -NoTypeInformation
$oneDriveSites | Export-Csv "$($reportFolder)\raw_oneDriveSites.csv" -NoTypeInformation
$oneDriveStorage | Export-Csv "$($reportFolder)\raw_oneDriveStorage.csv" -NoTypeInformation
}
}
#==============================================
# Sype for Business Report
#==============================================
if ($reportSkypeForBusiness) {
Write-Output "$(Get-Date) : Processing Skype For Business Report"
# Total minutes (audio/video)
# Organized minutes
Write-Output "$(Get-Date) : --> Getting SfB organized minutes"
$uri1 = "https://graph.microsoft.com/$graphApiVersion/reports/getSkypeForBusinessOrganizerActivityMinuteCounts(period='D$($dPeriod)')"
$sfb1 = (Invoke-RestMethod -Method Get -Uri $uri1 -Headers $headerParams) | ConvertFrom-Csv
if ($saveRawData) {
$sfb1 | Export-Csv "$($reportFolder)\raw_SkypeForBusinessOrganizerActivityMinuteCounts.csv" -NoTypeInformation
}
# Participant minutes
Write-Output "$(Get-Date) : --> Getting SfB participant minutes"
$uri2 = "https://graph.microsoft.com/$graphApiVersion/reports/getSkypeForBusinessParticipantActivityMinuteCounts(period='D$($dPeriod)')"
$sfb2 = (Invoke-RestMethod -Method Get -Uri $uri2 -Headers $headerParams) | ConvertFrom-Csv
if ($saveRawData) {
$sfb2 | Export-Csv "$($reportFolder)\raw_SkypeForBusinessParticipantActivityMinuteCounts.csv" -NoTypeInformation
}
# Peer to peer minutes
Write-Output "$(Get-Date) : --> Getting SfB p2p minutes"
$uri3 = "https://graph.microsoft.com/$graphApiVersion/reports/getSkypeForBusinessPeerToPeerActivityMinuteCounts(period='D$($dPeriod)')"
$sfb3 = (Invoke-RestMethod -Method Get -Uri $uri3 -Headers $headerParams) | ConvertFrom-Csv
if ($saveRawData) {
$sfb3 | Export-Csv "$($reportFolder)\raw_SkypeForBusinessPeerToPeerActivityMinuteCounts.csv" -NoTypeInformation
}
# Assemble object
$SfbMinutes = "" | Select-Object Organized, Participated, PeerToPeer, Total
[int]$SfbMinutes.Organized = ($sfb1 | Measure-Object "Audio/Video" -Sum).sum
[int]$SfbMinutes.Participated = ($sfb2 | Measure-Object "Audio/Video" -Sum).sum
[int]$SfbMinutes.PeerToPeer = (($sfb3 | Measure-Object "Audio" -Sum).sum + ($sfb3 | Measure-Object "Video" -Sum).sum)
[int]$SfbMinutes.Total = $SfbMinutes.Organized + $SfbMinutes.Participated + $SfbMinutes.PeerToPeer
# Active user, conference and p2p sessions
# Active User Count
Write-Output "$(Get-Date) : --> Getting SfB active user count"
$uri = "https://graph.microsoft.com/$graphApiVersion/reports/getSkypeForBusinessActivityUserDetail(period='D$($dPeriod)')"
$activeUserCount = (Invoke-RestMethod -Method Get -Uri $uri -Headers $headerParams) | ConvertFrom-Csv
$activeUserCount | Add-Member -MemberType ScriptProperty -Name LastActivityDate -Value { [datetime]$this."Last Activity Date" }
if ($saveRawData) {
$activeUserCount | Export-Csv "$($reportFolder)\raw_SkypeForBusinessActivityUserDetail.csv" -NoTypeInformation
}
$activeUserCount = ($activeUserCount | Where-Object { $_.LastActivityDate -ge $startDate -and $_.LastActivityDate -le $endDate }).Count
# Conference count
Write-Output "$(Get-Date) : --> Getting SfB conference count"
$uri = "https://graph.microsoft.com/$graphApiVersion/reports/getSkypeForBusinessOrganizerActivityCounts(period='D$($dPeriod)')"
$conferenceCount = (Invoke-RestMethod -Method Get -Uri $uri -Headers $headerParams) | ConvertFrom-Csv
if ($saveRawData) {
$conferenceCount | Export-Csv "$($reportFolder)\raw_SkypeForBusinessOrganizerActivityCounts.csv" -NoTypeInformation
}
$conferenceCount = $conferenceCount | Measure-Object -Property IM, "Audio/Video", "App Sharing", Web, "Dial-in/out 3rd Party", "Dial-in/out Microsoft" -Sum
$conferenceCount = ($conferenceCount | Measure-Object Sum -Sum).Sum
# Peer to peer count
Write-Output "$(Get-Date) : --> Getting SfB p2p activity count"
$uri = "https://graph.microsoft.com/$graphApiVersion/reports/getSkypeForBusinessPeerToPeerActivityCounts(period='D$($dPeriod)')"
$peerTOpeerCount = (Invoke-RestMethod -Method Get -Uri $uri -Headers $headerParams) | ConvertFrom-Csv
$peerTOpeerCount | Add-Member -MemberType ScriptProperty -Name ReportDate -Value { [datetime]$this."Report Date" }
$peerTOpeerCount = $peerTOpeerCount | Where-Object { $_.ReportDate -ge $startDate -and $_.ReportDate -le $endDate }
if ($saveRawData) {
$peerTOpeerCount | Export-Csv "$($reportFolder)\raw_SkypeForBusinessPeerToPeerActivityCounts.csv" -NoTypeInformation
}
$peerTOpeerCount = $peerTOpeerCount | Measure-Object -Property IM, Audio, Video, "App Sharing", "File Transfer" -Sum
$peerTOpeerCount = ($peerTOpeerCount | Measure-Object Sum -Sum).Sum
$sfbCount = "" | Select-Object ActiveUser, Conference, PeerToPeer
[int]$sfbCount.ActiveUser = $activeUserCount
[int]$sfbCount.Conference = $conferenceCount
[int]$sfbCount.PeerToPeer = $peerTOpeerCount
$html += '<table id="mainTable"><tr><th class="section"><img src="' + $skypeIconFile + '"></th><th class="section">Skype for Business Activity</th></tr></table><table id="mainTable">'
$html += '<tr><th>Audio & Video Minutes</th><td>' + ("{0:N0}" -f $sfbMinutes.Total) + '</td></tr>'
$html += '<tr><th>Active Users</th><td>' + ("{0:N0}" -f $sfbCount.ActiveUser) + '</td></tr>'
$html += '<tr><th>Conferences</th><td>' + ("{0:N0}" -f $sfbCount.Conference) + '</td></tr>'
$html += '<tr><th>Peer-To-Peer Sessions</th><td>' + ("{0:N0}" -f $sfbCount.PeerToPeer) + '</td></tr>'
$html += '<tr><td class="placeholder"> </td></tr></table>'
# Device usage distribution