-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGet-TenantUsers.ps1
More file actions
1547 lines (1353 loc) · 56.1 KB
/
Get-TenantUsers.ps1
File metadata and controls
1547 lines (1353 loc) · 56.1 KB
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
Generates comprehensive user inventory reports from Azure AD/Entra ID tenants using Microsoft Graph API.
.DESCRIPTION
This script connects to Microsoft Graph API headlessly using application credentials to enumerate all users within specified Azure AD/Entra ID tenant(s).
It retrieves detailed user information including account status, administrative roles, licensing, group memberships, and authentication activity. Instead of PowerShell modules it uses raw Graph API calls which increases reliability.
The script can process either a single tenant or multiple tenants from a CSV file, generating both summary and detailed reports
in CSV format as well as interactive HTML reports with tabbed sections for different user categories.
Key features:
- Enumerates all user types (Regular Users, Administrators, Guest Users)
- Identifies Global Administrators and other privileged roles
- Retrieves licensing information and usage statistics
- Tracks sign-in activity and account status
- Optional group membership enumeration
- Supports batch processing of multiple tenants
- Generates interactive HTML reports with filtering capabilities
- Provides security-focused analytics and recommendations
- Robust error handling with detailed failure reporting
.PARAMETER TenantId
The Azure AD/Entra ID Tenant ID (GUID format) for single tenant processing.
Required when not using CSV file input.
Example: "12345678-1234-1234-1234-123456789abc"
.PARAMETER ClientId
The Application (Client) ID of the registered Azure AD application with appropriate Microsoft Graph permissions.
Required when not using CSV file input.
Example: "87654321-4321-4321-4321-abcdef123456"
.PARAMETER ClientSecret
The client secret (application password) for the registered Azure AD application.
Required when not using CSV file input.
Note: Ensure this value is kept secure and consider using Azure Key Vault or other secure storage methods.
.PARAMETER CsvPath
Path to a CSV file containing multiple client tenant information for batch processing.
When specified, individual credential parameters are ignored.
Required CSV columns:
- Client: Display name for the tenant/organization
- Tenant ID: Azure AD Tenant ID
- Client ID: Application ID with Graph permissions
- Key Value: Client secret for the application
Example: "C:\Scripts\client-credentials.csv"
.PARAMETER ClientName
When using CSV input, specifies a specific client to process instead of all clients in the CSV.
Must match the value in the "Client" column exactly.
Example: "Contoso Corporation"
.PARAMETER IncludeAllProperties
Retrieves all available user properties from Microsoft Graph instead of the default subset.
This provides more comprehensive user information but may impact performance for large tenants.
Default behavior retrieves: id, userPrincipalName, displayName, mail, givenName, surname,
jobTitle, accountEnabled, userType, createdDateTime, signInActivity, assignedLicenses, onPremisesSyncEnabled
.PARAMETER IncludeGroupMemberships
Retrieves group membership information for each user account.
This provides detailed group membership data but significantly increases processing time for large tenants.
Note: Requires Group.Read.All permission, adds substantial processing overhead.
.OUTPUTS
For single tenant:
- UserInventory-[ClientName]-[timestamp].html: Interactive HTML report with tabbed sections
- Users-[ClientName]-[timestamp].csv: Detailed user data export
For multiple tenants:
- UserInventory-Report-[timestamp]/ folder containing:
- Individual tenant HTML and CSV reports
- UserInventory-AllTenants-[timestamp].csv: Consolidated summary
- MasterUserInventory-[timestamp].html: Multi-tenant dashboard
.NOTES
Author: Geoff Tankersley
Version: 1.0
Prerequisites:
- PowerShell 5.1 or later
- Internet connectivity to Microsoft Graph API endpoints
- Required Graph API Permissions:
- User.Read.All (Application permission)
- Directory.Read.All (Application permission)
- RoleManagement.Read.Directory (Application permission)
- Organization.Read.All (Application permission)
- Group.Read.All (Application permission) - if using IncludeGroupMemberships
Security Considerations:
- Client secrets should be stored securely
- Application should use least-privilege permissions
- Consider using certificate-based authentication for production
- Audit application access regularly
- Review Global Administrator accounts regularly (Microsoft recommends 2-4 per tenant)
Performance Notes:
- Large tenants may take significant time to process
- IncludeGroupMemberships parameter adds substantial processing overhead
Security Analytics:
- Identifies excessive Global Administrator accounts
- Highlights guest user accounts requiring review
- Reports on disabled accounts with active licenses
- Tracks last sign-in activity for admin accounts
- Provides license utilization statistics
.EXAMPLE
.\Get-UserInventory.ps1 -TenantId "12345678-1234-1234-1234-123456789abc" -ClientId "87654321-4321-4321-4321-abcdef123456" -ClientSecret "your-client-secret"
Processes a single tenant and generates individual user inventory reports.
.EXAMPLE
.\Get-UserInventory.ps1 -CsvPath "C:\Scripts\clients.csv"
Processes all tenants listed in the CSV file and generates consolidated user inventory reports.
.EXAMPLE
.\Get-UserInventory.ps1 -CsvPath "C:\Scripts\clients.csv" -ClientName "Contoso Corporation"
Processes only the "Contoso Corporation" tenant from the CSV file.
.EXAMPLE
.\Get-UserInventory.ps1 -TenantId "12345678-1234-1234-1234-123456789abc" -ClientId "87654321-4321-4321-4321-abcdef123456" -ClientSecret "your-client-secret" -IncludeAllProperties -IncludeGroupMemberships
Processes a single tenant with comprehensive user properties and group membership data.
.EXAMPLE
.\Get-UserInventory.ps1 -CsvPath "C:\Scripts\clients.csv" -ClientName "Contoso" -IncludeAllProperties
Processes a specific tenant from CSV with extended user properties but without group memberships for faster processing.
#>
param(
[Parameter(Mandatory=$false)]
[string]$TenantId,
[Parameter(Mandatory=$false)]
[string]$ClientId,
[Parameter(Mandatory=$false)]
[string]$ClientSecret,
[Parameter(Mandatory=$false)]
[string]$CsvPath,
[Parameter(Mandatory=$false)]
[string]$ClientName,
[Parameter(Mandatory=$false)]
[switch]$IncludeAllProperties,
[Parameter(Mandatory=$false)]
[switch]$IncludeGroupMemberships
)
# Validate parameter combo
if (-not $CsvPath -and (-not $TenantId -or -not $ClientId -or -not $ClientSecret)) {
Write-Host "Error: You must provide either:" -ForegroundColor Red
Write-Host " 1. Individual parameters: -TenantId, -ClientId, and -ClientSecret" -ForegroundColor Yellow
Write-Host " 2. CSV file with -CsvPath (optionally with -ClientName for specific client)" -ForegroundColor Yellow
Write-Host "`nExample usage:" -ForegroundColor Cyan
Write-Host " # Single tenant" -ForegroundColor Gray
Write-Host " .\script.ps1 -TenantId 'xxx' -ClientId 'xxx' -ClientSecret 'xxx'" -ForegroundColor Gray
Write-Host " # All tenants from CSV" -ForegroundColor Gray
Write-Host " .\script.ps1 -CsvPath 'clients.csv'" -ForegroundColor Gray
Write-Host " # Specific client from CSV" -ForegroundColor Gray
Write-Host " .\script.ps1 -CsvPath 'clients.csv' -ClientName 'Client1'" -ForegroundColor Gray
exit 1
}
if ($CsvPath -and (-not (Test-Path $CsvPath))) {
Write-Host "Error: CSV file not found at path: $CsvPath" -ForegroundColor Red
exit 1
}
function Import-ClientCsv {
param (
[string]$Path
)
try {
$clients = Import-Csv -Path $Path
# Validate required columns
$requiredColumns = @('Client', 'Tenant ID', 'Client ID', 'Key Value')
$csvColumns = $clients[0].PSObject.Properties.Name
foreach ($requiredColumn in $requiredColumns) {
if ($requiredColumn -notin $csvColumns) {
throw "Missing required column: '$requiredColumn'. Required columns: $($requiredColumns -join ', ')"
}
}
Write-Host "Successfully loaded $($clients.Count) clients from CSV" -ForegroundColor Green
return $clients
}
catch {
Write-Host "Error loading CSV file: $_" -ForegroundColor Red
throw
}
}
function Get-ClientFromCsv {
param (
[array]$Clients,
[string]$ClientName
)
$client = $Clients | Where-Object { $_.Client -eq $ClientName }
if (-not $client) {
Write-Host "Client '$ClientName' not found in CSV. Available clients:" -ForegroundColor Red
$Clients | ForEach-Object { Write-Host " - $($_.Client)" -ForegroundColor Yellow }
throw "Client not found"
}
return $client
}
function Get-MsGraphToken {
param (
[Parameter(Mandatory=$true)]
[string]$TenantId,
[Parameter(Mandatory=$true)]
[string]$ClientId,
[Parameter(Mandatory=$true)]
[string]$ClientSecret
)
$tokenUrl = "https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token"
$body = @{
client_id = $ClientId
client_secret = $ClientSecret
scope = "https://graph.microsoft.com/.default"
grant_type = "client_credentials"
}
try {
$response = Invoke-RestMethod -Uri $tokenUrl -Method Post -Body $body -ContentType "application/x-www-form-urlencoded"
return $response.access_token
}
catch {
Write-Error "Error obtaining access token: $_"
throw $_
}
}
function Get-TenantBasicInfo {
param (
[Parameter(Mandatory=$true)]
[string]$AccessToken,
[Parameter(Mandatory=$false)]
[string]$TenantId
)
$headers = @{
"Authorization" = "Bearer $AccessToken"
"Content-Type" = "application/json"
}
try {
$domainUri = "https://graph.microsoft.com/v1.0/domains"
$domainsResponse = Invoke-RestMethod -Uri $domainUri -Method Get -Headers $headers
$initialDomain = ($domainsResponse.value | Where-Object { $_.isInitial -eq $true }).id
if (-not $initialDomain) {
$initialDomain = "unknown.onmicrosoft.com"
}
$displayName = "Unknown"
try {
$orgUri = "https://graph.microsoft.com/v1.0/organization"
$orgResponse = Invoke-RestMethod -Uri $orgUri -Method Get -Headers $headers
$displayName = $orgResponse.value[0].displayName
}
catch {
Write-Verbose "Could not retrieve organization display name: $_"
if ($TenantId) {
$displayName = "Tenant $TenantId"
}
}
return [PSCustomObject]@{
TenantId = $TenantId
DisplayName = $displayName
InitialDomain = $initialDomain
VerifiedDomains = ($domainsResponse.value | ForEach-Object { $_.id }) -join ", "
}
}
catch {
Write-Warning "Error retrieving tenant information: $_"
# Return minimal info
return [PSCustomObject]@{
TenantId = $TenantId
DisplayName = "Unknown"
InitialDomain = "unknown.onmicrosoft.com"
VerifiedDomains = ""
}
}
}
function Get-TenantUsers {
param (
[Parameter(Mandatory=$true)]
[string]$AccessToken,
[Parameter(Mandatory=$false)]
[switch]$IncludeAllProperties
)
$headers = @{
"Authorization" = "Bearer $AccessToken"
"Content-Type" = "application/json"
"ConsistencyLevel" = "eventual"
}
try {
$select = "id,userPrincipalName,displayName,mail,givenName,surname,jobTitle,accountEnabled,userType,createdDateTime,signInActivity,assignedLicenses,onPremisesSyncEnabled"
if ($IncludeAllProperties) {
$select = "*"
}
$users = @()
$nextLink = "https://graph.microsoft.com/v1.0/users?`$select=$select&`$top=100"
$batchCounter = 0
do {
$batchCounter++
Write-Progress -Activity "Retrieving Users" -Status "Batch $batchCounter" -Id 1
$response = Invoke-RestMethod -Uri $nextLink -Method Get -Headers $headers
$users += $response.value
$nextLink = $response.'@odata.nextLink'
Write-Host "Retrieved batch $batchCounter - Added $($response.value.Count) users (Total: $($users.Count))" -ForegroundColor Cyan
# Small delay to avoid throttling
if ($nextLink) {
Start-Sleep -Milliseconds 100
}
} while ($nextLink)
Write-Progress -Activity "Retrieving Users" -Id 1 -Completed
return $users
}
catch {
Write-Error "Error retrieving users: $_"
throw $_
}
}
function Get-TenantRoles {
param (
[Parameter(Mandatory=$true)]
[string]$AccessToken
)
$headers = @{
"Authorization" = "Bearer $AccessToken"
"Content-Type" = "application/json"
}
try {
$roles = @()
$nextLink = "https://graph.microsoft.com/v1.0/directoryRoles?`$expand=members"
do {
$response = Invoke-RestMethod -Uri $nextLink -Method Get -Headers $headers
$roles += $response.value
$nextLink = $response.'@odata.nextLink'
} while ($nextLink)
return $roles
}
catch {
Write-Error "Error retrieving directory roles: $_"
throw $_
}
}
function Get-TenantLicenses {
param (
[Parameter(Mandatory=$true)]
[string]$AccessToken
)
$headers = @{
"Authorization" = "Bearer $AccessToken"
"Content-Type" = "application/json"
}
try {
# Get SKUs
$licensesUri = "https://graph.microsoft.com/v1.0/subscribedSkus"
$response = Invoke-RestMethod -Uri $licensesUri -Method Get -Headers $headers
return $response.value
}
catch {
Write-Error "Error retrieving license information: $_"
throw $_
}
}
function Get-UserGroupMemberships {
param (
[Parameter(Mandatory=$true)]
[string]$AccessToken,
[Parameter(Mandatory=$true)]
[string]$UserId
)
$headers = @{
"Authorization" = "Bearer $AccessToken"
"Content-Type" = "application/json"
}
try {
# Get group membership
$memberOfUri = "https://graph.microsoft.com/v1.0/users/$UserId/memberOf"
$response = Invoke-RestMethod -Uri $memberOfUri -Method Get -Headers $headers
# Filter to just security groups and mail-enabled security groups
$groups = $response.value | Where-Object { $_.'@odata.type' -eq '#microsoft.graph.group' }
return $groups
}
catch {
Write-Warning "Error retrieving group memberships for user $UserId`: $_"
return @()
}
}
function Format-UserData {
param (
[Parameter(Mandatory=$true)]
[array]$Users,
[Parameter(Mandatory=$true)]
[array]$Roles,
[Parameter(Mandatory=$true)]
[array]$Licenses,
[Parameter(Mandatory=$false)]
[switch]$IncludeGroupMemberships,
[Parameter(Mandatory=$true)]
[string]$AccessToken
)
# License lookups
$licenseLookup = @{}
foreach ($license in $Licenses) {
$licenseLookup[$license.skuId] = @{
SkuPartNumber = $license.skuPartNumber
ConsumedUnits = $license.consumedUnits
AvailableUnits = $license.prepaidUnits.enabled - $license.consumedUnits
}
}
$adminRolesLookup = @{}
# Process Global Admin roles
$globalAdminRole = $Roles | Where-Object { $_.displayName -eq "Global Administrator" -or $_.displayName -eq "Company Administrator" }
if ($globalAdminRole) {
foreach ($member in $globalAdminRole.members) {
if (-not $adminRolesLookup.ContainsKey($member.id)) {
$adminRolesLookup[$member.id] = @()
}
$adminRolesLookup[$member.id] += "Global Administrator"
}
}
foreach ($role in $Roles) {
if ($role.displayName -eq "Global Administrator" -or $role.displayName -eq "Company Administrator") {
continue # Already processed
}
foreach ($member in $role.members) {
if (-not $adminRolesLookup.ContainsKey($member.id)) {
$adminRolesLookup[$member.id] = @()
}
$adminRolesLookup[$member.id] += $role.displayName
}
}
$formattedUsers = @()
$totalUsers = $Users.Count
$currentUser = 0
foreach ($user in $Users) {
$currentUser++
Write-Progress -Activity "Processing User Data" -Status "User $currentUser of $totalUsers" -PercentComplete (($currentUser / $totalUsers) * 100)
# Get user roles
$userRoles = if ($adminRolesLookup.ContainsKey($user.id)) { $adminRolesLookup[$user.id] -join ", " } else { "None" }
# Get user licenses
$userLicenses = @()
foreach ($license in $user.assignedLicenses) {
if ($licenseLookup.ContainsKey($license.skuId)) {
$userLicenses += $licenseLookup[$license.skuId].SkuPartNumber
}
else {
$userLicenses += $license.skuId
}
}
# Get last sign-in time
$lastSignIn = if ($user.signInActivity.lastSignInDateTime) { $user.signInActivity.lastSignInDateTime } else { "Never" }
# Get group memberships
$groupMemberships = @()
if ($IncludeGroupMemberships) {
$groups = Get-UserGroupMemberships -AccessToken $AccessToken -UserId $user.id
$groupMemberships = ($groups | Select-Object -ExpandProperty displayName) -join ", "
}
# Determine user category
$userCategory = "Regular"
if ($userRoles -like "*Global Administrator*") {
$userCategory = "Global Admin"
}
elseif ($userRoles -ne "None") {
$userCategory = "Admin"
}
elseif ($user.userType -eq "Guest") {
$userCategory = "Guest"
}
$formattedUser = [PSCustomObject]@{
UserPrincipalName = $user.userPrincipalName
DisplayName = $user.displayName
FirstName = $user.givenName
LastName = $user.surname
JobTitle = $user.jobTitle
Mail = $user.mail
UserType = $user.userType
AccountEnabled = $user.accountEnabled
CreatedDate = $user.createdDateTime
LastSignIn = $lastSignIn
AdminRoles = $userRoles
Category = $userCategory
Licenses = $userLicenses -join ", "
LicenseCount = $user.assignedLicenses.Count
IsOnPremisesSynced = $user.onPremisesSyncEnabled
Groups = $groupMemberships
UserId = $user.id
}
$formattedUsers += $formattedUser
}
Write-Progress -Activity "Processing User Data" -Completed
return $formattedUsers
}
function Get-UserInventoryHtml {
param (
[Parameter(Mandatory=$true)]
[string]$TenantName,
[Parameter(Mandatory=$true)]
[string]$TenantDomain,
[Parameter(Mandatory=$true)]
[array]$FormattedUsers
)
$totalUsers = $FormattedUsers.Count
$globalAdmins = ($FormattedUsers | Where-Object { $_.Category -eq "Global Admin" }).Count
$otherAdmins = ($FormattedUsers | Where-Object { $_.Category -eq "Admin" }).Count
$guestUsers = ($FormattedUsers | Where-Object { $_.UserType -eq "Guest" }).Count
$disabledUsers = ($FormattedUsers | Where-Object { $_.AccountEnabled -eq $false }).Count
$licensedUsers = ($FormattedUsers | Where-Object { $_.LicenseCount -gt 0 }).Count
$onPremUsers = ($FormattedUsers | Where-Object { $_.IsOnPremisesSynced -eq $true }).Count
$guestPercentage = [math]::Round(($guestUsers / $totalUsers) * 100, 2)
$disabledPercentage = [math]::Round(($disabledUsers / $totalUsers) * 100, 2)
$properAccountsCount = ($FormattedUsers | Where-Object { $_.AccountEnabled -eq $true -and $_.UserType -ne "Guest" -and $_.LicenseCount -gt 0 }).Count
$properAccountsPercentage = [math]::Round(($properAccountsCount / $totalUsers) * 100, 2)
$licenseDistribution = @{}
foreach ($user in $FormattedUsers) {
if ($user.Licenses) {
$licenses = $user.Licenses -split ", "
foreach ($license in $licenses) {
if (-not $licenseDistribution.ContainsKey($license)) {
$licenseDistribution[$license] = 0
}
$licenseDistribution[$license]++
}
}
}
$topLicenses = $licenseDistribution.GetEnumerator() | Sort-Object -Property Value -Descending | Select-Object -First 5
$globalAdminRows = ""
foreach ($user in ($FormattedUsers | Where-Object { $_.Category -eq "Global Admin" } | Sort-Object -Property DisplayName)) {
$statusClass = if ($user.AccountEnabled) { "enabled" } else { "disabled" }
$globalAdminRows += @"
<tr>
<td>$($user.DisplayName)</td>
<td>$($user.UserPrincipalName)</td>
<td>$($user.JobTitle)</td>
<td class="$statusClass">$($user.AccountEnabled)</td>
<td>$($user.LastSignIn)</td>
<td>$($user.Licenses)</td>
</tr>
"@
}
$otherAdminRows = ""
foreach ($user in ($FormattedUsers | Where-Object { $_.Category -eq "Admin" } | Sort-Object -Property DisplayName)) {
$statusClass = if ($user.AccountEnabled) { "enabled" } else { "disabled" }
$otherAdminRows += @"
<tr>
<td>$($user.DisplayName)</td>
<td>$($user.UserPrincipalName)</td>
<td>$($user.JobTitle)</td>
<td>$($user.AdminRoles)</td>
<td class="$statusClass">$($user.AccountEnabled)</td>
<td>$($user.LastSignIn)</td>
<td>$($user.Licenses)</td>
</tr>
"@
}
$guestUserRows = ""
foreach ($user in ($FormattedUsers | Where-Object { $_.UserType -eq "Guest" } | Sort-Object -Property DisplayName)) {
$statusClass = if ($user.AccountEnabled) { "enabled" } else { "disabled" }
$guestUserRows += @"
<tr>
<td>$($user.DisplayName)</td>
<td>$($user.UserPrincipalName)</td>
<td>$($user.CreatedDate)</td>
<td class="$statusClass">$($user.AccountEnabled)</td>
<td>$($user.LastSignIn)</td>
</tr>
"@
}
$disabledUserRows = ""
foreach ($user in ($FormattedUsers | Where-Object { $_.AccountEnabled -eq $false } | Sort-Object -Property DisplayName)) {
$disabledUserRows += @"
<tr>
<td>$($user.DisplayName)</td>
<td>$($user.UserPrincipalName)</td>
<td>$($user.UserType)</td>
<td>$($user.Category)</td>
<td>$($user.LastSignIn)</td>
<td>$($user.Licenses)</td>
</tr>
"@
}
# HTML Template
$html = @"
<!DOCTYPE html>
<html>
<head>
<title>User Inventory Report - $TenantName</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
background-color: #f5f5f5;
color: #333;
}
h1, h2, h3 {
color: #0078D4;
margin-top: 0;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
.card {
background-color: white;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
padding: 15px;
margin-bottom: 20px;
overflow: hidden;
}
.header-card {
background-color: #E5F1FA;
}
.dashboard {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
gap: 20px;
margin-bottom: 20px;
}
.dashboard-card {
text-align: center;
padding: 15px;
}
.dashboard-number {
font-size: 36px;
font-weight: bold;
margin: 10px 0;
}
.dashboard-label {
font-size: 14px;
color: #666;
}
table {
border-collapse: collapse;
width: 100%;
margin-bottom: 10px;
font-size: 0.9rem;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
th {
background-color: #0078D4;
color: white;
position: sticky;
top: 0;
}
tr:hover {
background-color: #f5f5f5;
}
.enabled { color: #107C10; }
.disabled { color: #E81123; }
.admin { color: #0078D4; font-weight: bold; }
.global-admin { color: #E81123; font-weight: bold; }
.guest { color: #FF8C00; }
.table-container {
max-height: 400px;
overflow-y: auto;
margin-bottom: 10px;
}
.search-box {
width: 100%;
padding: 8px;
margin-bottom: 15px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 1rem;
}
.tab-container {
margin-bottom: 15px;
}
.tab-button {
background-color: #f0f0f0;
border: none;
padding: 10px 20px;
cursor: pointer;
font-weight: bold;
border-radius: 4px 4px 0 0;
}
.tab-button.active {
background-color: #0078D4;
color: white;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.percentage-box {
background-color: #f9f9f9;
border-radius: 6px;
padding: 15px;
margin: 15px 0;
border-left: 4px solid #0078D4;
}
.percentage-item {
display: flex;
justify-content: space-between;
margin-bottom: 10px;
align-items: center;
}
.percentage-label {
font-weight: bold;
}
.percentage-bar-container {
flex-grow: 1;
margin: 0 15px;
background-color: #e0e0e0;
height: 12px;
border-radius: 6px;
overflow: hidden;
}
.percentage-bar {
height: 100%;
width: 0%; /* Will be set by inline style */
border-radius: 6px;
}
.percentage-value {
min-width: 60px;
text-align: right;
}
.proper-accounts { background-color: #107C10; }
.guest-accounts { background-color: #FF8C00; }
.disabled-accounts { background-color: #E81123; }
</style>
<script>
function filterTable(tableId) {
var input = document.getElementById('searchInput-' + tableId);
var filter = input.value.toUpperCase();
var table = document.getElementById(tableId);
var rows = table.getElementsByTagName('tr');
for (var i = 1; i < rows.length; i++) {
var found = false;
var cells = rows[i].getElementsByTagName('td');
for (var j = 0; j < cells.length; j++) {
var cell = cells[j];
if (cell) {
var text = cell.textContent || cell.innerText;
if (text.toUpperCase().indexOf(filter) > -1) {
found = true;
break;
}
}
}
if (found) {
rows[i].style.display = '';
} else {
rows[i].style.display = 'none';
}
}
}
function openTab(evt, tabName) {
var i, tabContent, tabButtons;
tabContent = document.getElementsByClassName('tab-content');
for (i = 0; i < tabContent.length; i++) {
tabContent[i].classList.remove('active');
}
tabButtons = document.getElementsByClassName('tab-button');
for (i = 0; i < tabButtons.length; i++) {
tabButtons[i].classList.remove('active');
}
document.getElementById(tabName).classList.add('active');
evt.currentTarget.classList.add('active');
}
</script>
</head>
<body>
<div class="container">
<div class="card header-card">
<h1>User Inventory Report</h1>
<p><strong>Tenant:</strong> $TenantName</p>
<p><strong>Domain:</strong> $TenantDomain</p>
<p><strong>Generated:</strong> $(Get-Date -Format "yyyy-MM-dd HH:mm:ss")</p>
</div>
<div class="dashboard">
<div class="dashboard-card card">
<div class="dashboard-label">Total Users</div>
<div class="dashboard-number">$totalUsers</div>
</div>
<div class="dashboard-card card">
<div class="dashboard-label">Global Admins</div>
<div class="dashboard-number" style="color: #E81123;">$globalAdmins</div>
</div>
<div class="dashboard-card card">
<div class="dashboard-label">Other Admins</div>
<div class="dashboard-number" style="color: #0078D4;">$otherAdmins</div>
</div>
<div class="dashboard-card card">
<div class="dashboard-label">Guest Users</div>
<div class="dashboard-number" style="color: #FF8C00;">$guestUsers</div>
</div>
<div class="dashboard-card card">
<div class="dashboard-label">Disabled Users</div>
<div class="dashboard-number" style="color: #E81123;">$disabledUsers</div>
</div>
<div class="dashboard-card card">
<div class="dashboard-label">Licensed Users</div>
<div class="dashboard-number" style="color: #107C10;">$licensedUsers</div>
</div>
</div>
<div class="tab-container">
<button class="tab-button active" onclick="openTab(event, 'tab-global-admins')">Global Admins</button>
<button class="tab-button" onclick="openTab(event, 'tab-other-admins')">Other Admins</button>
<button class="tab-button" onclick="openTab(event, 'tab-guest-users')">Guest Users</button>
<button class="tab-button" onclick="openTab(event, 'tab-disabled-users')">Disabled Users</button>
<button class="tab-button" onclick="openTab(event, 'tab-all-users')">All Users</button>
<button class="tab-button" onclick="openTab(event, 'tab-licenses')">License Summary</button>
</div>
<div id="tab-global-admins" class="tab-content card active">
<h2>Global Administrators ($globalAdmins)</h2>
<input type="text" id="searchInput-globalAdmins" class="search-box" onkeyup="filterTable('globalAdmins')" placeholder="Search global admins...">
<div class="table-container">
<table id="globalAdmins">
<tr>
<th>Name</th>
<th>Username</th>
<th>Job Title</th>
<th>Enabled</th>
<th>Last Sign-in</th>
<th>Licenses</th>
</tr>
$globalAdminRows
</table>
</div>
</div>
<div id="tab-other-admins" class="tab-content card">
<h2>Other Administrators ($otherAdmins)</h2>
<input type="text" id="searchInput-otherAdmins" class="search-box" onkeyup="filterTable('otherAdmins')" placeholder="Search other admins...">
<div class="table-container">
<table id="otherAdmins">
<tr>
<th>Name</th>
<th>Username</th>
<th>Job Title</th>
<th>Admin Roles</th>
<th>Enabled</th>
<th>Last Sign-in</th>
<th>Licenses</th>
</tr>
$otherAdminRows
</table>
</div>
</div>
<div id="tab-guest-users" class="tab-content card">
<h2>Guest Users ($guestUsers)</h2>
<input type="text" id="searchInput-guestUsers" class="search-box" onkeyup="filterTable('guestUsers')" placeholder="Search guest users...">
<div class="table-container">
<table id="guestUsers">
<tr>
<th>Name</th>
<th>Username</th>
<th>Created Date</th>
<th>Enabled</th>
<th>Last Sign-in</th>
</tr>
$guestUserRows
</table>
</div>
</div>
<div id="tab-disabled-users" class="tab-content card">
<h2>Disabled Users ($disabledUsers)</h2>
<input type="text" id="searchInput-disabledUsers" class="search-box" onkeyup="filterTable('disabledUsers')" placeholder="Search disabled users...">
<div class="table-container">
<table id="disabledUsers">
<tr>
<th>Name</th>
<th>Username</th>
<th>User Type</th>
<th>Category</th>
<th>Last Sign-in</th>
<th>Licenses</th>
</tr>
$disabledUserRows
</table>
</div>
</div>
<div id="tab-all-users" class="tab-content card">
<h2>All Users ($totalUsers)</h2>
<input type="text" id="searchInput-allUsers" class="search-box" onkeyup="filterTable('allUsers')" placeholder="Search all users...">
<div class="table-container">
<table id="allUsers">
<tr>
<th>Name</th>
<th>Username</th>
<th>User Type</th>
<th>Category</th>