-
Notifications
You must be signed in to change notification settings - Fork 12
/
Get-RubrikM365SizingInfo.ps1
1843 lines (1696 loc) · 103 KB
/
Get-RubrikM365SizingInfo.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
<#
.SYNOPSIS
Get-RubrikM365SizingInfo.ps1 returns M365 usage information for a subscription.
.DESCRIPTION
Get-RubrikM365SizingInfo.ps1 returns M365 usage information for a subscprtion.
Data is gathered using the Microsoft Graph APIs and Exchange module.
The usage data should be similar to the metrics in the Admin Center under each
workload's "Usage Reports" data. There could be some discrepency between the
"Total Users" shown in the Usage Charts and what the script gathers because the
script uses the detailed user .CSV and summarizes that information.
The M365 Usage Reports do not contain information on Exchange In Place Archives.
By default, the script will try to gather this information by looping through
each user that has an In Place Archive and gathering that info directly. Unfortunately,
if there are a lot of users, this may time out the script. If that is the case,
you can use the flag to skip gathering in place archive data and try to provide
an estimate.
The M365 Usage Reports do not contain information on Exchange Recoverable Items Folder.
By default, the script will try to gather this information by looping through
every user and gathering that info directly. Unfortunately,
if there are a lot of users, this may time out the script. If that is the case,
you can use the flag to skip gathering Recoverable Items data and try to provide
an estimate.
.EXAMPLE
PS C:\> .\Get-RubrikM365SizingInfo.ps1
Opens a browser window to authenticate to M365 Graph APIs and Microsoft Exchange
Module to pull usage information.
PS C:\> .\Get-RubrikM365SizingInfo.ps1 -AnnualGrowth 35
Calculate sizing to include a 35% annual growth rate
PS C:\> .\Get-RubrikM365SizingInfo.ps1 -SkipArchiveMailbox $true
Skip gathering In Place Archive mailboxes.
PS C:\> .\Get-RubrikM365SizingInfo.ps1 SkipRecoverableItems $true
Skip gathering Recoverable Items hierarchy.
PS C:\> .\Get-RubrikM365SizingInfo.ps1 -ADGroup <ad_group_name>
Gather user info for only the AD Group specified.
.NOTES
Author: Chris Lumnah
Created Date: 6/17/2021
Updated: 7/9/24
By: Steven Tong
Updated: 26/08/24
By: Sameer Arora
#>
[CmdletBinding()]
param (
[Parameter()]
[bool]$EnableDebug = $false,
# Provide your estimated annual growth rate, eg '10' for 10%
[Parameter(HelpMessage="Estimated annual growth rate, eg 10 for 10%")]
[int]$AnnualGrowth,
# Provide AD Group name if you only want to gather data for a specific AD Group
[Parameter()]
[String]$ADGroup,
# Provide AD Group name to exclude if you want to exclude it from sizing
[Parameter()]
[String]$ExcludeADGroup,
# If gathering AD Group, CSV file to output AD Group membership info
[Parameter()]
[String]$ADGroupCSVFilename = './adgrouplist.csv',
# Whether or not to skip gathering archived mailboxes, which can timeout
[Parameter()]
[bool]$SkipArchiveMailbox = $false,
# Whether or not to skip gathering Recoverable Items fodler items, which can timeout
[Parameter()]
[bool]$SkipRecoverableItems = $true,
# Number of days to get historical stats for: 7, 30, 90, 180
[Parameter()]
[Int]$Period = 180
)
$date = Get-Date
$dateString = $date.ToString("yyyy-MM-dd")
$dateStringHH = $date.ToString("yyyy-MM-dd_HHmm")
# Filename to export the html report to
$outFilename = "./Rubrik-M365-Sizing-$dateStringHH.html"
# Folder to export CSVs to
$ExportFolder = '.'
$Version = "6.3"
$ProgressPreference = 'SilentlyContinue'
# Define the capacity metric conversions
$GB = 1000000000
$GiB = 1073741824
$TB = 1000000000000
$TiB = 1099511627776
# Set which capacity metric to use
$capacityMetric = $GB
$capacityDisplay = 'GB'
Write-Host "Starting the Rubrik Microsoft 365 sizing script ($Version)."
$ExchangeHTMLTitle = "User"
if ($AnnualGrowth -eq '') {
$AnnualGrowth = 30
}
# Function to use Graph APIs to download report info
Function Get-MgReport {
[CmdletBinding()]
param (
# MS Graph API report name
[Parameter(Mandatory)]
[String]$ReportName,
# Report Period (Days)
[Parameter()]
[ValidateSet("7", "30", "90", "180")]
[String]$Period
)
try {
if ($reportName -eq 'getMailboxUsageDetail' -or $reportName -eq 'getMailboxUsageStorage') {
$graphApiVersion = "Beta"
} else {
$graphApiVersion = "Beta"
}
if ($Period -ne '') {
Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/$($graphApiVersion)/reports/$($ReportName)(period=`'D$($Period)`')" -OutputFilePath "$ExportFolder\$ReportName.csv"
} else {
Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/$($graphApiVersion)/reports/$($ReportName)" -OutputFilePath "$ExportFolder\$ReportName.csv"
}
return "$ExportFolder\$ReportName.csv"
}
catch {
$errorMessage = $_.Exception | Out-String
if ($errorMessage.Contains('Response status code does not indicate success: Forbidden (Forbidden)')) {
Disconnect-MgGraph
throw "The user account used for authentication must have permissions covered by Reports Reader admin role."
}
throw $_.Exception
}
}
# Function to calculate annual growth based on historical report
# This may not be a good representation of actual growth in an environment
# if many changes are happening - for example, a migration event which would
# inflate steady state growth numbers.
function Measure-AverageGrowth {
param (
[Parameter(Mandatory)]
[string]$ReportCSV,
[Parameter(Mandatory)]
[string]$ReportName
)
$UsageReport = Import-Csv -Path $ReportCSV | Sort-Object -Property "Report Date" -Descending
$ReportDays = $UsageReport[0].'Report Period'
$LatestUsageGB = [math]::Round($UsageReport[0].'Storage Used (Byte)' / 1GB, 2)
$EarliestUsageGB = [math]::Round($UsageReport[-1].'Storage Used (Byte)' / 1GB, 2)
$GrowthOverPeriod = [math]::Round($LatestUsageGB - $EarliestUsageGB, 2)
$AvgGrowthPerDay = $GrowthOverPeriod / $ReportDays
$GrowthPerYearGB = [math]::Round($AvgGrowthPerDay * 365, 2)
$GrowthPerYearPct = [math]::Round($GrowthPerYearGB / $LatestUsageGB, 2)
Write-Host "$ReportName historical storage usage:"
Write-Host " - Usage on $($UsageReport[0].'Report Date'): $LatestUsageGB GB"
Write-Host " - Usage on $($UsageReport[-1].'Report Date'): $EarliestUsageGB GB"
Write-Host " - Growth over $ReportDays days: $GrowthOverPeriod GB"
Write-Host " - Growth annualized per year: $GrowthPerYearGB GB, $($GrowthPerYearPct * 100)%"
return $GrowthPerYearPct
}
# Function to solve for licenses required
# Query M365Licsolver Azure Function
function Solve-License {
param (
[Parameter(Mandatory)]
[int]$userLicense,
[Parameter(Mandatory)]
[int]$storageGB
)
# If less than 76GB Average per user then query the azure function that calculates the best mix of subscription types. If more than 76 then Unlimited is the best option.
if (($storageGB) / $userLicense -le 76) {
# Query the M365Licsolver Azure Function
$SolverQuery = '{"users":"' + $userLicense + '","data":"' + $storageGB + '"}'
try {
$APIReturn = ConvertFrom-JSON (Invoke-WebRequest 'https://m365licsolver-azure.azurewebsites.net:/api/httpexample' -ContentType "application/json" -Body $SolverQuery -UseBasicParsing -Method 'POST')
}
catch {
$errorMessage = $_.Exception | Out-String
if ($errorMessage.Contains('Response status code does not indicate success: 404')) {
Write-Host "[Info] Unable to calculate license recommendations."
}
}
$FiveGBUsers = $APIReturn.FiveGBSubscriptions * 10
$TwentyGBUsers = $APIReturn.TwentyGBSubscriptions * 10
$FiftyGBUsers = $APIReturn.FiftyGBSubscriptions * 10
$UnlimitedGBUsers = 0
} else {
$FiveGBUsers = 0
$TwentyGBUsers = 0
$FiftyGBUsers = 0
$UnlimitedGBPacks = [math]::ceiling($userLicense / 10)
$UnlimitedGBUsers = $UnlimitedGBPacks * 10
}
$licenseRequired = [PSCustomObject] @{
"FiveGBUsers" = $FiveGBUsers
"TwentyGBUsers" = $TwentyGBUsers
"FiftyGBUsers" = $FiftyGBUsers
"UnlimitedGBUsers" = $UnlimitedGBUsers
}
return $licenseRequired
}
# function to get folder items, size, and name for the Recoverable Items folder in both Primary and In-Place mailbox for a single user.
function Get-RecoverableItemsInfo {
param (
[Parameter(Mandatory = $true, HelpMessage = "Enter the user mailbox to be checked.")]
[string]$Mailbox,
[Parameter(Mandatory = $true, HelpMessage = "Enter whether to include In-Place archive mailbox Recoverable Items folder or not.")]
[bool]$IncludeArchiveMailbox,
[Parameter()]
[bool]$EnableDebug = $false
)
# Aggreagate folder statistics for the supported Recoverable Items folders
$RIFItemsStatistics = [PSCustomObject] @{
"UserPrincipalName" = $Mailbox
"RIFSize" = 0
"RIFItems" = 0
}
# Get folder statistics for the supported Recoverable Items folders
$recoverableItemsSpecialFolders = @(
"/Deletions",
"/Purges",
"/Versions",
"/DiscoveryHolds"
)
try {
$primaryStats = Get-MailboxFolderStatistics -Identity $Mailbox -FolderScope RecoverableItems | Where-Object {
$recoverableItemsSpecialFolders -contains $_.FolderPath
}
} catch {
Write-Error "Error retrieving folder statistics. $_"
}
if ($primaryStats.Count -eq 0) {
Write-Output "No Recoverable Items folders found for primary mailbox $Mailbox."
}
if ($IncludeArchiveMailbox) {
try {
$inPlaceStats = Get-MailboxFolderStatistics -Identity $Mailbox -FolderScope RecoverableItems -Archive | Where-Object {
$recoverableItemsSpecialFolders -contains $_.FolderPath
}
} catch {
Write-Error "Error retrieving folder statistics. $_"
}
if ($inPlaceStats.Count -eq 0) {
Write-Output "No Recoverable Items folders found for In-Place mailbox $Mailbox."
}
}
# Format and display the results
$folderStats = $primaryStats + $inPlaceStats
foreach ($stats in $folderStats) {
$sizeInBytes = $stats.FolderSize -match '\(([^)]+) bytes\)'
$sizeInBytes = [long]($Matches[1] -replace ',', '')
$RIFItemsStatistics.RIFSize += $sizeInBytes
if ($EnableDebug) {
Write-Host "folder "$($stats.FolderPath)" size found $sizeInBytes , cummulative $RIFItemsStatistics"
}
}
$totalItems = $folderStats | Measure-Object -Property 'ItemsInFolder' -Sum
$RIFItemsStatistics.RIFItems += $totalItems.sum
if ($EnableDebug) {
Write-Output "total items found "$($totalItems.sum)" , cummulative $RIFItemsStatistics"
}
return $RIFItemsStatistics
}
function Get-AccessToken {
param (
[string]$ClientId,
[string]$ClientSecret,
[string]$TenantId,
[string]$Scope = "https://outlook.office365.com/.default"
)
$body = @{
client_id = $ClientId
scope = $Scope
client_secret = $ClientSecret
grant_type = "client_credentials"
}
$url = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"
try {
$response = Invoke-RestMethod -Method Post -Uri $url -ContentType "application/x-www-form-urlencoded" -Body $body
return $response.access_token
} catch {
Write-Error "Failed to get access token: $_"
return $null
}
}
# Validate that Period (days) for historical reports is valid
# Must be: 7, 30, 90, or 180
$PeriodValues = @(7, 30, 90, 180)
if ($Period -in $PeriodValues) {
} else {
throw "Error: Period (days) needs to be: 7, 30, 90, or 180"
}
# Validate the required 'Microsoft.Graph.Reports' is installed
# and provide a user friendly message when it's not.
if (Get-Module -ListAvailable -Name Microsoft.Graph.Reports) {
} else {
throw "The 'Microsoft.Graph.Reports' module is required for this script. Run the follow command to install: Install-Module Microsoft.Graph.Reports"
}
# Validate the required 'ExchangeOnlineManagement' is installed and provide a user friendly message when it's not.
if (Get-Module -ListAvailable -Name ExchangeOnlineManagement) {
} else {
throw "The 'ExchangeOnlineManagement' module is required for this script. Run the follow command to install: Install-Module ExchangeOnlineManagement"
}
$AzureAdRequired = $PSBoundParameters.ContainsKey('ADGroup') -or $PSBoundParameters.ContainsKey('ExcludeADGroup')
if ($AzureAdRequired) {
# Validate the required 'Azure.Graph.Authentication' is installed
# and provide a user friendly message when it's not.
if (Get-Module -ListAvailable -Name Microsoft.Graph.Groups) {
} else {
throw "The 'Microsoft.Graph.Groups' module is required for filtering by a specific Azure AD Group. Run the follow command to install: Install-Module Microsoft.Graph.Groups"
}
}
Write-Host "Choose one of the following options for accessing Exchange Online"
$useApp = Read-Host -Prompt "1 for using app credentials, 2 for using user access"
if ($useApp -eq "1") {
# Prompt the user to enter the Client ID, Client Secret, and Tenant ID
Write-Host "Enter app info to authenticate for Graph Access"
$tenantId = Read-Host -Prompt "Enter your Tenant ID"
$clientId = Read-Host -Prompt "Enter your Azure AD Application Client ID"
$ClientSecretCredential = Get-Credential -Credential $clientId
Write-Host "[INFO] Connecting to the Microsoft Graph API using 'Reports.Read.All', 'User.Read.All', and 'Group.Read.All' permissions."
try {
Connect-MgGraph -TenantId $tenantId -ClientSecretCredential $clientSecretCredential
}
catch {
$errorException = $_.Exception
$errorMessage = $errorException.Message
Write-Host "[ERROR] Unable to Connect to the Microsoft Graph PowerShell Module: $errorMessage"
return
}
if ($SkipArchiveMailbox -eq $false -or $SkipRecoverableItems -eq $false) {
Write-Host "Connecting to the Microsoft Exchange Online Module to gather per-mailbox In Place Archive stats."
try {
$clientSecretSecure = Read-Host -Prompt "Password for user $clientId" -AsSecureString
$clientSecret = ConvertFrom-SecureString -SecureString $clientSecretSecure -AsPlainText
$token = Get-AccessToken -clientId $clientId -clientSecret $clientSecret -tenantId $tenantId
Connect-ExchangeOnline -AccessToken $token -Organization $tenantId
} catch {
$errorException = $_.Exception
$errorMessage = $errorException.Message
Write-Host "[ERROR] Unable to Connect to the Microsoft Exchange PowerShell Module: $errorMessage"
return
}
}
} elseif ($useApp -eq "2") {
Write-Host "[INFO] Connecting to the Microsoft Graph API using 'Reports.Read.All', 'User.Read.All', and 'Group.Read.All' permissions."
try {
Connect-MgGraph -Scopes "Reports.Read.All", "User.Read.All", "Group.Read.All" | Out-Null
}
catch {
$errorException = $_.Exception
$errorMessage = $errorException.Message
Write-Host "[ERROR] Unable to Connect to the Microsoft Graph PowerShell Module: $errorMessage"
return
}
if ($SkipArchiveMailbox -eq $false -or $SkipRecoverableItems -eq $false) {
Write-Host "Connecting to the Microsoft Exchange Online Module to gather per-mailbox In Place Archive stats."
try {
Connect-ExchangeOnline -ShowBanner:$false
} catch {
$errorException = $_.Exception
$errorMessage = $errorException.Message
Write-Host "[ERROR] Unable to Connect to the Microsoft Exchange PowerShell Module: $errorMessage"
return
}
}
} else {
Write-Host "Invalid option, please choose either 1 or 2."
return
}
# If AD Group is provided, get the AD Group membership info
if ($AzureAdRequired) {
Write-Host "Looking up AD Group users in: $ADGroup" -foregroundcolor green
$AzureAdGroupDetails = Get-MgGroup -Filter "DisplayName eq '$ADGroup'"
if ($AzureAdGroupDetails.Count -eq 0) {
throw "The Azure AD Group '$ADGroup' does not exist. Exiting script."
}
$AzureAdGroupMembersById = Get-MgGroupTransitiveMember -GroupId $AzureAdGroupDetails.Id -All
if ($EnableDebug) {
Write-Host "[DEBUG] Azure AD Group Members Size: $($AzureAdGroupMembersById.Count)"
}
$AzureAdGroupMembersByUserPrincipalName = @()
$AzureAdGroupMembersById | Foreach-Object {
if ($_.AdditionalProperties["@odata.type"] -eq "#microsoft.graph.user") {
$AzureAdGroupMembersByUserPrincipalName += $_.AdditionalProperties["userPrincipalName"]
}
}
if ($AzureAdGroupMembersByUserPrincipalName.Count -eq 0) {
throw "The Azure AD Group '$ADGroup' does not contain any User Principal Names."
}
Write-Host "# of Azure AD Group members found: $($AzureAdGroupMembersByUserPrincipalName.Count)" -foregroundcolor green
Write-Host "AD Group user principal names exported to CSV: $ADGroupCSVFilename" -foregroundcolor green
$AzureAdGroupMembersByUserPrincipalName | Out-File -Path $ADGroupCSVFilename
}
if ($EnableDebug) {
try {
$user = Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/v1.0/me"
$permissions = Get-MgUserOauth2PermissionGrant -UserId $user.id
Write-Host "[DEBUG] The authenticated user account has the following permissions:$($permissions.Scope)"
}
catch {
$errorMessage = $_.Exception | Out-String
throw $_.Exception
}
}
Write-Host ""
Write-Host "The data gathered here is the same as in the M365 Admin Center" -foreground green
Write-Host "under Reports -> Usage -> <Workload> -> Usage Reports"
Write-Host "Microsoft metrics could differ a bit depending on what you are looking at"
Write-Host ""
### Exchange - Get reports for Exchange and process them
Write-Host "*** Retrieving usage info for: Exchange ***" -foregroundcolor green
Write-Host "Data will be gathered from the chart data and per-mailbox usage report" -foregroundcolor green
Write-Host "Getting chart data - this should match the chart for the Users drop-down and Total mailboxes" -foregroundcolor green
$ReportCSV = Get-MgReport -ReportName 'getMailboxUsageMailboxCounts' -Period $Period
Write-Host "Exchange chart CSV saved to: $ReportCSV" -foregroundcolor green
$ExchangeChartData = Import-Csv -Path $ReportCSV
Write-Host "Total # of User (non-shared mailboxes) - chart data: $($ExchangeChartData[0].total)" -foregroundcolor green
Write-Host ""
# Get Exchange per user usage report
Write-Host "Getting the per-mailbox usage report - this should match the details in the Admin Center reports" -foregroundcolor green
$ReportCSV = Get-MgReport -ReportName 'getMailboxUsageDetail' -Period $Period
Write-Host "Exchange per-mailbox usage CSV saved to: $ReportCSV" -foregroundcolor green
$ExchangeUsageReport = Import-Csv -Path $ReportCSV
$ExchangeTotalUsersCount = $ExchangeUsageReport.count
$ExchangeNonDeletedUsersCount = $($ExchangeUsageReport | Where-Object { $_.'Is Deleted' -eq 'FALSE' }).count
$ExchangeDeletedUsersCount = $($ExchangeUsageReport | Where-Object { $_.'Is Deleted' -eq 'TRUE' }).count
Write-Host "Total # of mailboxes - from usage report: $ExchangeTotalUsersCount"
Write-Host "Total # of deleted mailboxes - from usage report: $ExchangeDeletedUsersCount"
Write-Host "Total # of active (non-deleted) mailboxes - from usage report: $ExchangeNonDeletedUsersCount"
Write-Host "Now performing additional filtering..."
Write-Host ""
# List of all active (non-deleted) user mailboxes
$ExchangeUsageReportUsers = $ExchangeUsageReport | Where-Object { $_.'Is Deleted' -eq 'FALSE' -and
$_.'Recipient Type' -ne 'Shared'}
# List of all active (non-deleted) shared mailboxes
$ExchangeUsageReportShared = $ExchangeUsageReport | Where-Object { $_.'Is Deleted' -eq 'FALSE' -and
$_.'Recipient Type' -eq 'Shared'}
$ExchangeActiveUsers = $ExchangeUsageReportUsers + $ExchangeUsageReportShared
if ($AzureAdRequired) {
if ($ADGroup -ne '') {
Write-Host "Filtering user mailboxes by Azure AD Group: $ADGroup"
} else {
}
$FilterByField = "User Principal Name"
$ExchangeUsageReportUsers = $ExchangeUsageReportUsers | Where-Object { $_.$FilterByField -in $AzureAdGroupMembersByUserPrincipalName }
# If we didn't get any usage for the Azure AD group users, it might be because the reports are masking User IDs
if ($ExchangeUsageReportUsers.count -eq 0) {
Write-Host "[ERROR] Did not match any Azure AD Group users to the usage reports" -foregroundcolor red
Write-Host "[ERROR] Check the Azure AD group csv ($ADGroupCSVFilename) to see what users are part of the Azure AD Group" -foregroundcolor red
Write-Host "[ERROR] Check the mailbox csv ($reportCSV) to see if 'User Principal Name' are being masked" -foregroundcolor red
Write-Host "[ERROR] Un-mask by going to M365 Admin Center -> Settings -> Org Settings -> Services" -foregroundcolor red
Write-Host "[ERROR] Then click on Reports and clear: Display concealed user, group, and site names in all reports, and then select Save" -foregroundcolor red
Write-Host "[ERROR] See: https://learn.microsoft.com/en-us/microsoft-365/troubleshoot/miscellaneous/reports-show-anonymous-user-name" -foregroundcolor red
throw "Error running script with Azure AD group option - could not find any matching users. Exiting script."
}
Write-Host "Matched $($ExchangeUsageReportUsers.count) users in the provided Azure AD Group" -foregroundcolor green
}
# Calculate metrics for user mailboxes
$userMailboxStorageSum = $ExchangeUsageReportUsers | Measure-Object -Property 'Storage Used (Byte)' -Sum
$userMailboxStorageSumDisplay = [math]::Round($userMailboxStorageSum.Sum / $capacityMetric, 2)
$userMailboxItems = $ExchangeUsageReportUsers | Measure-Object -Property 'Item Count' -Sum
# Calculate metrics for shared mailboxes
$sharedMailboxStorageSum = $ExchangeUsageReportShared | Measure-Object -Property 'Storage Used (Byte)' -Sum
$sharedMailboxStorageSumDisplay = [math]::Round($sharedMailboxStorageSum.Sum / $capacityMetric, 2)
$sharedMailboxItems = $ExchangeUsageReportShared | Measure-Object -Property 'Item Count' -Sum
Write-Host "Total # of active user mailboxes - from usage report: $($ExchangeUsageReportUsers.count)" -foregroundcolor green
Write-Host "Active users storage used (not including in-place archve, Recoverable Items Folder): $userMailboxStorageSumDisplay $capacityDisplay" -foregroundcolor green
Write-Host "Active users item count (not including in-place archve, Recoverable Items Folder): $($userMailboxItems.sum)" -foregroundcolor green
Write-Host "Total # of active shared mailboxes - from usage report: $($ExchangeUsageReportShared.count)" -foregroundcolor green
Write-Host "Shared mailboxes storage used: $sharedMailboxStorageSumDisplay $capacityDisplay" -foregroundcolor green
Write-Host "Shared mailboxes item count (not including in-place archve, Recoverable Items Folder): $($sharedMailboxItems.sum)" -foregroundcolor green
Write-Host ""
Write-Host "Getting historical Exchange storage growth" -foregroundcolor green
$ReportCSV = Get-MgReport -ReportName 'getMailboxUsageStorage' -Period $Period
$CalculatedGrowth = Measure-AverageGrowth -ReportCSV $ReportCSV -ReportName 'Exchange'
$ExchangeDetails = [PSCustomObject] @{
"Chart User Mailboxes" = $ExchangeChartData[0].total
"Total Mailboxes" = $($ExchangeUsageReportUsers.count + $ExchangeUsageReportShared.count)
"User Mailboxes" = $ExchangeUsageReportUsers.count
"User Storage Used No Archive" = $userMailboxStorageSum.sum
"User Items No Archive" = $userMailboxItems.sum
"Shared Mailboxes" = $ExchangeUsageReportShared.count
"Shared Storage Used No Archive" = $sharedMailboxStorageSum.sum
"Shared Items No Archive" = $sharedMailboxItems.sum
"Total Storage Used" = $($userMailboxStorageSum.sum + $sharedMailboxStorageSum.sum)
"Total Items" = $($userMailboxItems.sum + $sharedMailboxItems.sum)
"Calculated Growth %" = $CalculatedGrowth
}
### OneDrive - Get reports for OneDrive and process them
Write-Host "*** Retrieving usage info for: OneDrive ***" -foregroundcolor green
Write-Host "Data will be gathered from the chart data and per-account usage report" -foregroundcolor green
Write-Host "Getting chart data - this should match the chart for Total Accounts" -foregroundcolor green
$ReportCSV = Get-MgReport -ReportName 'getOneDriveUsageAccountCounts' -Period $Period
Write-Host "OneDrive account chart CSV saved to: $ReportCSV" -foregroundcolor green
$OneDriveChartAccount = Import-Csv -Path $ReportCSV
Write-Host "Total # of OneDrive accounts - chart data: $($OneDriveChartAccount[0].total)" -foregroundcolor green
Write-Host ""
Write-Host "Getting chart data - this should match the chart for Total Storage" -foregroundcolor green
$ReportCSV = Get-MgReport -ReportName 'getOneDriveUsageStorage' -Period $Period
Write-Host "OneDrive storage chart CSV saved to: $ReportCSV" -foregroundcolor green
$OneDriveChartStorage = Import-Csv -Path $ReportCSV
$OneDriveChartStorageUsed = [math]::round($OneDriveChartStorage[0].'Storage Used (Byte)' / $capacityMetric, 2)
Write-Host "Total # of OneDrive storage - chart data: $oneDriveChartStorageUsed $capacityDisplay" -foregroundcolor green
Write-Host ""
Write-Host "Getting chart data - this should match the chart for Total Files" -foregroundcolor green
$ReportCSV = Get-MgReport -ReportName 'getOneDriveUsageFileCounts' -Period $Period
Write-Host "OneDrive files chart CSV saved to: $ReportCSV" -foregroundcolor green
$OneDriveChartFiles = Import-Csv -Path $ReportCSV
Write-Host "Total # of OneDrive files - chart data: $($OneDriveChartFiles[0].total)" -foregroundcolor green
Write-Host ""
Write-Host "Getting the per-account usage report - this should match the details in the Admin Center reports" -foregroundcolor green
Write-Host "However, this count may not match the Total count in the chart" -foregroundcolor green
$ReportCSV = Get-MgReport -ReportName 'getOneDriveUsageAccountDetail' -Period $Period
Write-Host "OneDrive per-account usage CSV saved to: $ReportCSV" -foregroundcolor green
$OneDriveUsageReport = Import-Csv -Path $ReportCSV
$OneDriveTotalUsersCount = $OneDriveUsageReport.count
$OneDriveNonDeletedUsersCount = $($OneDriveUsageReport | Where-Object { $_.'Is Deleted' -eq 'FALSE' }).count
$OneDriveDeletedUsersCount = $($OneDriveUsageReport | Where-Object { $_.'Is Deleted' -eq 'TRUE' }).count
Write-Host "Total # of accounts - from usage report: $($OneDriveUsageReportAccounts.count)"
Write-Host "Total # of deleted accounts - from usage report: $OneDriveDeletedUsersCount"
Write-Host "Total # of active (non-deleted) accounts - from usage report: $OneDriveNonDeletedUsersCount"
Write-Host "Now performing additional filtering..."
Write-Host ""
$OneDriveUsageReportAccounts = $OneDriveUsageReport | Where-Object { $_.'Is Deleted' -eq 'FALSE' }
if ($AzureAdRequired) {
Write-Host "Filtering user accounts by Azure AD Group: $ADGroup"
$FilterByField = "Owner Principal Name"
$OneDriveUsageReportAccounts = $OneDriveUsageReportAccounts | Where-Object { $_.$FilterByField -in $AzureAdGroupMembersByUserPrincipalName }
# If we didn't get any usage for the Azure AD group users, it might be because the reports are masking User IDs
if ($OneDriveUsageReportAccounts.count -eq 0) {
Write-Host "[ERROR] Did not match any Azure AD Group users to the usage reports" -foregroundcolor red
Write-Host "[ERROR] Check the Azure AD group csv ($ADGroupCSVFilename) to see what users are part of the Azure AD Group" -foregroundcolor red
Write-Host "[ERROR] Check the OneDrive csv ($reportCSV) to see if 'Owner Principal Name' are being masked" -foregroundcolor red
Write-Host "[ERROR] Un-mask by going to M365 Admin Center -> Settings -> Org Settings -> Services" -foregroundcolor red
Write-Host "[ERROR] Then click on Reports and clear: Display concealed user, group, and site names in all reports, and then select Save" -foregroundcolor red
Write-Host "[ERROR] See: https://learn.microsoft.com/en-us/microsoft-365/troubleshoot/miscellaneous/reports-show-anonymous-user-name" -foregroundcolor red
throw "Error running script with Azure AD group option - could not find any matching users. Exiting script."
}
Write-Host "Matched $($OneDriveUsageReportAccounts.count) users in the provided Azure AD Group" -foregroundcolor green
}
# Calculate metrics for OneDrive accounts
$oneDriveStorageSum = $OneDriveUsageReportAccounts | Measure-Object -Property 'Storage Used (Byte)' -Sum
$oneDriveStorageSumDisplay = [math]::Round($oneDriveStorageSum.Sum / $capacityMetric, 2)
$oneDriveFiles = $OneDriveUsageReportAccounts | Measure-Object -Property 'File Count' -Sum
Write-Host "Total # of Accounts - from usage report: $($OneDriveUsageReportAccounts.count)" -foregroundcolor green
Write-Host "Accounts storage used: $oneDriveStorageSumDisplay $capacityDisplay" -foregroundcolor green
Write-Host "Accounts file count: $($oneDriveFiles.sum)" -foregroundcolor green
Write-Host ""
Write-Host "Getting historical OneDrive storage growth" -foregroundcolor green
$ReportCSV = Get-MgReport -ReportName 'getOneDriveUsageStorage' -Period $Period
$CalculatedGrowth = Measure-AverageGrowth -ReportCSV $ReportCSV -ReportName 'Exchange'
$OneDriveDetails = [PSCustomObject] @{
"Chart Accounts" = $OneDriveChartAccount[0].total
"Chart Storage Used" = $OneDriveChartStorage[0].'Storage Used (Byte)'
"Chart Files" = $OneDriveChartFiles[0].total
"Usage Accounts" = $OneDriveUsageReportAccounts.count
"Usage Account Storage Used" = $oneDriveStorageSum.sum
"Usage Account Files" = $oneDriveFiles.sum
"Calculated Growth %" = $CalculatedGrowth
}
# If AD Group is specified, assume each user is licensed so use that count
if ($AzureAdRequired) {
$OneDriveDetails | Add-Member -MemberType NoteProperty -Name 'Accounts' -Value $OneDriveDetails.'Usage Accounts'
$OneDriveDetails | Add-Member -MemberType NoteProperty -Name 'Storage Used' -Value $OneDriveDetails.'Usage Account Storage Used'
$OneDriveDetails | Add-Member -MemberType NoteProperty -Name 'Total Files' -Value $OneDriveDetails.'Usage Account Files'
} else {
# Otherwise, use the counts from the Chart
$OneDriveDetails | Add-Member -MemberType NoteProperty -Name 'Accounts' -Value $OneDriveDetails.'Chart Accounts'
$OneDriveDetails | Add-Member -MemberType NoteProperty -Name 'Storage Used' -Value $OneDriveDetails.'Chart Storage Used'
$OneDriveDetails | Add-Member -MemberType NoteProperty -Name 'Total Files' -Value $OneDriveDetails.'Chart Files'
}
### SharePoint - Get reports for SharePoint and process them
Write-Host "*** Retrieving usage info for: SharePoint ***" -foregroundcolor green
Write-Host "Data will be gathered site usage report" -foregroundcolor green
Write-Host "Getting site usage report" -foregroundcolor green
$ReportCSV = Get-MgReport -ReportName 'getSharePointSiteUsageDetail' -Period $Period
Write-Host "SharePoint site usage CSV saved to: $ReportCSV" -foregroundcolor green
$SharePointUsageReport = Import-Csv -Path $ReportCSV
# Calculate metrics for SharePoint Sites
$SharePointSitesCount = $SharePointUsageReport.count
$SharePointNonDeletedSitesCount = $($SharePointUsageReportSites | Where-Object { $_.'Is Deleted' -eq 'FALSE' }).count
$SharePointDeletedSitesCount = $($SharePointUsageReportSites | Where-Object { $_.'Is Deleted' -eq 'TRUE' }).count
Write-Host "Total # of sites - from usage report: $SharePointSitesCount"
Write-Host "Total # of deleted mailboxes - from usage report: $SharePointDeletedSitesCount"
Write-Host "Total # of active (non-deleted) mailboxes - from usage report: $SharePointNonDeletedSitesCount"
Write-Host "Now performing additional filtering..."
Write-Host ""
$SharePointUsageReportSites = $SharePointUsageReport | Where-Object { $_.'Is Deleted' -eq 'FALSE' }
# Calculate metrics for SharePoint sites
$sharePointStorageSum = $SharePointUsageReportSites | Measure-Object -Property 'Storage Used (Byte)' -Sum
$sharePointStorageSumDisplay = [math]::Round($sharePointStorageSum.Sum / $capacityMetric, 2)
$sharePointFiles = $SharePointUsageReportSites | Measure-Object -Property 'File Count' -Sum
Write-Host "Total # of SharePoint Sites - from usage report: $($SharePointUsageReportSites.count)" -foregroundcolor green
Write-Host "SharePoint Sites storage used: $sharePointStorageSumDisplay $capacityDisplay" -foregroundcolor green
Write-Host "SharePoint Sites file count: $($sharePointFiles.sum)" -foregroundcolor green
Write-Host ""
Write-Host "Getting historical OneDrive storage growth" -foregroundcolor green
$ReportCSV = Get-MgReport -ReportName 'getSharePointSiteUsageStorage' -Period $Period
$CalculatedGrowth = Measure-AverageGrowth -ReportCSV $ReportCSV -ReportName 'Exchange'
$SharePointDetails = [PSCustomObject] @{
"Sites" = $SharePointUsageReportSites.count
"Sites Storage Used" = $sharePointStorageSum.sum
"Account Files" = $sharePointFiles.sum
"Calculated Growth %" = $CalculatedGrowth
}
Write-Host "[INFO] Disconnecting from the Microsoft Graph API."
Disconnect-MgGraph
# The Microsoft Exchange Reports do not contain In-Place Archive sizing information.DESCRIPTION
# We need to connect to the Exchange Online module to get this information
$ArchiveMailboxes = $ExchangeUsageReportUsers | Where-Object { $_.'Has Archive' -eq 'TRUE' }
$ArchiveMailboxesCount = $ArchiveMailboxes.Count
if ($SkipArchiveMailbox -eq $true) {
Write-Host "Skipping gathering In Place Archive usage" -foregroundcolor green
} else {
Write-Host "Now gathering In Place Archive usage" -foregroundcolor green
Write-Host "This may take awhile since stats need to be gathered per user" -foregroundcolor green
Write-Host "Progress will be written as they are gathered" -foregroundcolor green
Write-Host "If this keeps timing out, run script with -SkipArchiveMailbox $true option" -foregroundcolor green
$ConnectionUserPrincipalName = $(Get-ConnectionInformation).UserPrincipalName
# $ActionRequiredLogMessage = "[ACTION REQUIRED] In order to periodically refresh the connection to Microsoft, we need the User Principal Name used during the authentication process."
# $ActionRequiredPromptMessage = "Enter the User Principal Name"
$FirstInterval = 500
$SkipInternval = $FirstInterval
$ArchiveMailboxSizeGb = 0
$LargeAmountofArchiveMailboxCount = 5000
$FilterByField = 'User Principal Name'
Write-Host "[INFO] Retrieving all Exchange Mailbox In-Place Archive sizing"
# Get a list of all users with In Place Archive mailboxes in the tenant
# $ArchiveMailboxes = Get-ExoMailbox -Archive -ResultSize Unlimited
$ArchiveMailboxList = @()
$CurrentMailboxNum = 0
Write-Host "Found $ArchiveMailboxesCount mailboxes with In Place Archives" -foregroundcolor green
do {
if ( ($CurrentMailboxNum % 10) -eq 0 ) {
Write-Host "[$CurrentMailboxNum / $ArchiveMailboxesCount] Processing mailboxes ..."
}
$CurrentUser = $ArchiveMailboxes[$CurrentMailboxNum].'User Principal Name'
try {
$ArchiveMailboxStats = Get-EXOMailboxStatistics -Archive -Identity $CurrentUser
$MatchArchiveSize = $ArchiveMailboxStats.TotalItemSize -match '\(([^)]+) bytes\)'
$ArchiveSize = [long]($Matches[1] -replace ',', '')
$ArchiveStats = [PSCustomObject] @{
"UserPrincipalName" = $CurrentUser
"ArchiveSize" = $ArchiveSize
"ArchiveItems" = $ArchiveMailboxStats.ItemCount
}
$ArchiveMailboxList += $ArchiveStats
} catch {
Write-Error "Error getting info for mailbox: $CurrentUser"
}
$CurrentMailboxNum += 1
} while ($CurrentMailboxNum -lt $ArchiveMailboxesCount)
$ArchiveMeasurementSize = $ArchiveMailboxList | Measure-Object -Property 'ArchiveSize' -Sum -Average
$ArchiveMeasurementItems = $ArchiveMailboxList | Measure-Object -Property 'ArchiveItems' -Sum -Average
$TotalArchiveSize = [math]::Round($($ArchiveMeasurementSize.Sum / $capacityMetric), 2)
$TotalArchiveItems = $ArchiveMeasurementItems.Sum
Write-Host "Finished gathering stats on mailboxes with In Place Archive" -foregroundcolor green
Write-Host "Total # of mailboxes with In Place Archive: $ArchiveMailboxesCount" -foregroundcolor green
Write-Host "Total size of mailboxes with In Place Archive: $TotalArchiveSize $capacityDisplay" -foregroundcolor green
Write-Host "Total # of items of mailboxes with In Place Archive: $TotalArchiveItems" -foregroundcolor green
}
if ($SkipArchiveMailbox -eq $false) {
$ExchangeDetails | Add-Member -MemberType NoteProperty -Name 'Archive Mailboxes' -Value $ArchiveMailboxesCount
$ExchangeDetails | Add-Member -MemberType NoteProperty -Name 'Archive Storage Used' -Value $ArchiveMeasurementSize.Sum
$ExchangeDetails | Add-Member -MemberType NoteProperty -Name 'Archive Items' -Value $ArchiveMeasurementItems.Sum
$ExchangeTotalStorage = $ExchangeDetails.'Total Storage Used' + $ArchiveMeasurementSize.Sum
$ExchangeDetails.'Total Storage Used' = $ExchangeTotalStorage
$ExchangeTotalItems = $ExchangeDetails.'Total Items' + $ArchiveMeasurementItems.Sum
$ExchangeDetails.'Total Items' = $ExchangeTotalItems
} else {
$ExchangeDetails | Add-Member -MemberType NoteProperty -Name 'Archive Mailboxes' -Value "Skipped ($ArchiveMailboxesCount)"
$ExchangeDetails | Add-Member -MemberType NoteProperty -Name 'Archive Storage Used' -Value '-'
$ExchangeDetails | Add-Member -MemberType NoteProperty -Name 'Archive Items' -Value '-'
}
# The Microsoft Exchange Reports do not contain Recoverable Items sizing information.DESCRIPTION
# We need to connect to the Exchange Online module to get this information
# function to get folder items, size, and name for the Recoverable Items folder in both Primary and In-Place mailbox for passed users.
function Get-RIFMailboxStats {
param (
[Parameter(Mandatory = $true)]
[array]$ExchangeUsers,
[Parameter(Mandatory = $true, HelpMessage = "Enter whether to include In-Place archive mailbox Recoverable Items folder or not.")]
[bool]$IncludeArchiveMailbox
)
$RIFMailboxList = @()
$CurrentMailboxNum = 0
$ActiveMailboxesCount = $ExchangeUsers.count
Write-Host "Found $ActiveMailboxesCount mailboxes with Recoverable Items" -ForegroundColor Green
do {
if (($CurrentMailboxNum % 10) -eq 0) {
Write-Host "[$CurrentMailboxNum / $ActiveMailboxesCount] Processing mailboxes ..."
}
$CurrentUser = $ExchangeUsers[$CurrentMailboxNum].'User Principal Name'
try {
$RIFStats = Get-RecoverableItemsInfo -Mailbox $CurrentUser -IncludeArchiveMailbox $IncludeArchiveMailbox
$RIFMailboxList += $RIFStats
} catch {
Write-Error "Error getting info for mailbox: $CurrentUser"
}
$CurrentMailboxNum += 1
} while ($CurrentMailboxNum -lt $ActiveMailboxesCount)
return $RIFMailboxList
}
# Example usage:
# $ExchangeActiveUsers = [Array of users]
# $ActiveMailboxesCount = $ExchangeActiveUsers.Count
# $RIFMailboxList = Append-RIFMailboxList -ExchangeActiveUsers $ExchangeActiveUsers -ActiveMailboxesCount $ActiveMailboxesCount
if ($SkipRecoverableItems -eq $true) {
Write-Host "Skipping gathering Recoverable Items usage" -foregroundcolor green
$ExchangeDetails | Add-Member -MemberType NoteProperty -Name 'Recoverable Items' -Value "Skipped"
$ExchangeDetails | Add-Member -MemberType NoteProperty -Name 'Recoverable Items Used' -Value '-'
$ExchangeDetails | Add-Member -MemberType NoteProperty -Name 'Recoverable Items Count' -Value '-'
} else {
Write-Host "Now gathering Recoverable Items usage" -foregroundcolor green
Write-Host "This may take awhile since stats need to be gathered per user" -foregroundcolor green
Write-Host "Progress will be written as they are gathered" -foregroundcolor green
Write-Host "If this keeps timing out, run script with SkipRecoverableItems $true option" -foregroundcolor green
$ConnectionUserPrincipalName = $(Get-ConnectionInformation).UserPrincipalName
# $ActionRequiredLogMessage = "[ACTION REQUIRED] In order to periodically refresh the connection to Microsoft, we need the User Principal Name used during the authentication process."
# $ActionRequiredPromptMessage = "Enter the User Principal Name"
$FirstInterval = 500
$SkipInternval = $FirstInterval
$ArchiveMailboxSizeGb = 0
$LargeAmountofArchiveMailboxCount = 5000
$FilterByField = 'User Principal Name'
Write-Host "[INFO] Retrieving all Exchange Mailbox Recoverable Items sizing"
# Get a list of all users with Recoverable Items shared/non-shared mailboxes in the tenant
$NonArchiveMailboxes = $ExchangeActiveUsers | Where-Object { $_.'Has Archive' -eq 'FALSE' }
$ArchiveMailboxes = $ExchangeActiveUsers | Where-Object { $_.'Has Archive' -eq 'TRUE' }
$RIFMailboxList = Get-RIFMailboxStats -ExchangeUsers $NonArchiveMailboxes -IncludeArchiveMailbox 0
$RIFMailboxList += Get-RIFMailboxStats -ExchangeUsers $ArchiveMailboxes -IncludeArchiveMailbox 1
$RIFMailboxSize = $RIFMailboxList | Measure-Object -Property 'RIFSize' -Sum -Average
$RIFMailboxItems = $RIFMailboxList | Measure-Object -Property 'RIFItems' -Sum -Average
$TotalRIFSize = [math]::Round($($RIFMailboxSize.Sum / $capacityMetric), 2)
$TotalRIFItems = $RIFMailboxItems.Sum
Write-Host "Finished gathering stats on mailboxes with Recoverable Items" -foregroundcolor green
Write-Host "Total # of mailboxes with Recoverable Items: $ActiveMailboxesCount" -foregroundcolor green
Write-Host "Total size of mailboxes with Recoverable Items: $TotalRIFSize $capacityDisplay" -foregroundcolor green
Write-Host "Total # of items of mailboxes with Recoverable Items: $TotalRIFItems" -foregroundcolor green
$ExchangeDetails | Add-Member -MemberType NoteProperty -Name 'Recoverable Items' -Value $ActiveMailboxesCount
$ExchangeDetails | Add-Member -MemberType NoteProperty -Name 'Recoverable Items Used' -Value $TotalRIFSize
$ExchangeDetails | Add-Member -MemberType NoteProperty -Name 'Recoverable Items Count' -Value $TotalRIFItems
$ExchangeTotalStorage = $ExchangeDetails.'Total Storage Used' + $TotalRIFSize
$ExchangeDetails.'Total Storage Used' = $ExchangeTotalStorage
$ExchangeTotalItems = $ExchangeDetails.'Total Items' + $TotalRIFItems
$ExchangeDetails.'Total Items' = $ExchangeTotalItems
}
Write-Host "Calculating # of license needed:"
Write-Host "Exchange user mailboxes: $($ExchangeDetails.'User Mailboxes')"
Write-Host "Exchange shared mailboxes: $($ExchangeDetails.'Shared Mailboxes')"
Write-Host "OneDrive chart accounts: $($OneDriveDetails.'Chart Accounts')"
[int]$UserLicensesRequired = $($ExchangeDetails.'User Mailboxes')
if ([int]$ExchangeDetails.'Shared Mailboxes' -gt $UserLicensesRequired) {
$UserLicensesRequired = $ExchangeDetails.'Shared Mailboxes'
}
if ([int]$OneDriveDetails.'Accounts' -gt $UserLicensesRequired) {
$UserLicensesRequired = $OneDriveDetails.'Accounts'
}
Write-Host "# of licenses required: $UserLicensesRequired" -foregroundcolor green
$totalStorage = $ExchangeDetails.'Total Storage Used' + $OneDriveDetails.'Storage Used' +
$SharePointDetails.'Sites Storage Used'
$totalItems = $ExchangeDetails.'Total Items' + $OneDriveDetails.'Total Files' +
$SharePointDetails.'Account Files'
$totalStorageGB = [math]::round($totalStorage / 1GB, 2)
[int]$UserLicenseRequired10 = [int]$UserLicensesRequired * 1.1
[int]$UserLicenseRequired20 = [int]$UserLicensesRequired * 1.2
[int]$UserLicenseRequiredCustom = [int]$UserLicensesRequired * (1 + ($AnnualGrowth / 100))
$totalStorage10GB = [math]::round($totalStorage / 1GB * 1.1, 2)
$totalStorage20GB = [math]::round($totalStorage / 1GB * 1.2, 2)
$totalStorageCustomGB = [math]::round($totalStorage / 1GB * (1 + ($AnnualGrowth / 100)), 2)
$growth10 = Solve-License -userLicense $UserLicenseRequired10 -storageGB $totalStorage10GB
$growth20 = Solve-License -userLicense $UserLicenseRequired20 -storageGB $totalStorage20GB
$growthCustom = Solve-License -userLicense $UserLicenseRequiredCustom -storageGB $totalStorageCustomGB
#region HTML Code for Output
$HTML_CODE = @"
<!DOCTYPE html>
<html>
<!---->
<!---->
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<head>
<style>
body {
background-color: #f4f4f4
}
.card-container {
display: flex;
width: 100%;
align-items: center;
justify-content: center;
padding-bottom: 20px;
}
.card-header {
display: flex;
}
.card-header-logo {
flex-grow: 1;
}
.rubrik-snowflake {
padding-top: 15px;
}
.card-header-text {
display: flex;
align-items: center;
justify-content: center;
font-size: 1.9rem;
line-height: 2.4rem;
}
.navigation-bar {
display: flex;
background-color: #060745;
width: 100%;
top: 0;
left: 0;
position: fixed;
max-height: 82px;
}
.logo {
padding-top: 20px;
padding-left: 10px;
display: block;
max-width: 150px;
}
.nav-bar-text {
padding-top: 12px;
flex-grow: 1;
display: flex;
color: white;
align-items: center;
justify-content: center;
font-size: 1.9rem;
line-height: 2.4rem;
margin-bottom: 20px;
margin-top: 0;
}
.rubrik-logo path {
fill: white;
}
.margin {
padding-bottom: 130px;
}
.card {
box-shadow: 0 4px 10px 0 rgb(0 0 0 / 20%), 0 4px 20px 0 rgb(0 0 0 / 19%);
width: 98%;
padding: 0.01em 16px;
}
.styled-table {
margin: 25px 0;
width: 100%;
}
.styled-table thead tr {
text-align: left;
}
.styled-table th,
.styled-table td {
padding: 12px 15px;
}
</style>
</head>
<body>
<div class="navigation-bar">
<div class="logo">
<svg class="rubrik-logo" width=auto height="82">
<defs>
<style>
.cls-1 {
fill: #fff
}
.cls-1,
.cls-2 {
fill-rule: evenodd
}
</style>
<mask id="mask" x="13.3" y="0" width="12.35" height="12.27" maskUnits="userSpaceOnUse">
<g transform="translate(-.31 -.22)">
<g id="mask-2">