-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGet-PIMUsers.ps1
More file actions
2286 lines (2015 loc) · 106 KB
/
Get-PIMUsers.ps1
File metadata and controls
2286 lines (2015 loc) · 106 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
#Requires -Version 7.5.2
<#
.SYNOPSIS
Haalt alle PIM en permanente rol gebruikers op voor meerdere tenants
.DESCRIPTION
Dit script gebruikt Microsoft Graph API om alle gebruikers op te halen die:
- Een PIM-rol hebben (permanent of eligible)
- Permanente rollen hebben (zonder PIM)
- Vergelijkt PIM vs permanent gebruik per tenant
.PARAMETER ConfigFile
Pad naar het configuratie bestand (standaard: config.json)
.PARAMETER OutputPath
Pad waar de export bestanden worden opgeslagen (overschrijft config.json instelling)
.PARAMETER ReportOnly
Genereer alleen HTML rapport uit bestaande exports zonder nieuwe data op te halen
.EXAMPLE
.\Get-PIMUsers.ps1
.EXAMPLE
.\Get-PIMUsers.ps1 -ConfigFile "custom-config.json" -OutputPath "C:\Exports"
.EXAMPLE
.\Get-PIMUsers.ps1 -ReportOnly
.AUTEUR
PowerShell Script voor PIM & Permanent Role Rapportage
.VERSIE
0.1
#>
param(
[string]$ConfigFile = "config.json",
[string]$OutputPath = "",
[switch]$ReportOnly
)
# Versie informatie
$ProjectVersion = "0.1"
$LastEditDate = "2025-08-16"
# Functie voor het controleren en installeren van PowerShell modules
function Install-RequiredModules {
param(
[string[]]$ModuleNames
)
Write-Host "Controleren van benodigde PowerShell modules..." -ForegroundColor Cyan
foreach ($ModuleName in $ModuleNames) {
Write-Host "Verwerken van module: $ModuleName" -ForegroundColor White
$Module = Get-Module -ListAvailable -Name $ModuleName
if (-not $Module) {
Write-Host "Module '$ModuleName' niet gevonden. Bezig met installeren..." -ForegroundColor Yellow
try {
Install-Module -Name $ModuleName -Scope CurrentUser -Force -AllowClobber
Write-Host "Module '$ModuleName' succesvol geïnstalleerd." -ForegroundColor Green
}
catch {
Write-Error "Fout bij installeren van module '$ModuleName': $($_.Exception.Message)"
throw
}
}
else {
Write-Host "Module '$ModuleName' is al aanwezig." -ForegroundColor Green
}
# Importeer de module
Write-Host "Importeren van module '$ModuleName'..." -ForegroundColor White
try {
Import-Module -Name $ModuleName -Force -ErrorAction Stop
Write-Host "Module '$ModuleName' geïmporteerd." -ForegroundColor Green
}
catch {
Write-Error "Fout bij importeren van module '$ModuleName': $($_.Exception.Message)"
throw
}
}
Write-Host "Module controle voltooid." -ForegroundColor Green
}
# Functie om configuratie te laden
function Get-ScriptConfig {
param(
[string]$ConfigFile,
[string]$OutputPathOverride
)
# Standaard configuratie
$defaultConfig = @{
ExportSettings = @{
OutputFolder = "exports"
CreateDateSubfolders = $false
ArchiveOldReports = $true
MaxReportsToKeep = 10
}
ReportSettings = @{
IncludeTimestamp = $true
FileEncoding = "UTF8"
DateFormat = "yyyyMMdd_HHmmss"
IncludeServicePrincipals = $true
}
BackupSettings = @{
EnableBackup = $false
BackupRoot = "backups"
ExportBackupSubfolder = "exports"
ConfigBackupSubfolder = "config"
EnableExportBackup = $true
EnableConfigBackup = $true
ExportBackupRetention = 5
ConfigBackupRetention = 3
}
}
# Probeer configuratie bestand te laden
if (Test-Path $ConfigFile) {
try {
$configData = Get-Content $ConfigFile -Raw | ConvertFrom-Json
Write-Host "✓ Configuratie geladen uit: $ConfigFile" -ForegroundColor Green
# Override met geladen configuratie voor alle secties
$configSections = @('ExportSettings', 'ReportSettings', 'BackupSettings', 'HTMLSettings', 'PIMSettings', 'FilterSettings', 'ColumnSettings', 'MultiTenantSettings')
foreach ($section in $configSections) {
if ($configData.$section) {
if (-not $defaultConfig.ContainsKey($section)) {
$defaultConfig[$section] = @{}
}
foreach ($key in $configData.$section.PSObject.Properties.Name) {
$defaultConfig[$section][$key] = $configData.$section.$key
}
}
}
}
catch {
Write-Warning "Kon configuratie bestand niet laden: $($_.Exception.Message). Gebruik standaard instellingen."
}
}
else {
Write-Warning "Configuratie bestand niet gevonden: $ConfigFile. Gebruik standaard instellingen."
}
# Override output path als parameter is gegeven
if ($OutputPathOverride -and $OutputPathOverride -ne "") {
$defaultConfig.ExportSettings.OutputFolder = $OutputPathOverride
Write-Host "✓ Output pad overschreven via parameter: $OutputPathOverride" -ForegroundColor Yellow
}
return $defaultConfig
}
# Functie om export folder te maken en te beheren
function Initialize-ExportFolder {
param(
[hashtable]$Config
)
$outputFolder = $Config.ExportSettings.OutputFolder
# Maak absolute pad
if (-not [System.IO.Path]::IsPathRooted($outputFolder)) {
$outputFolder = Join-Path (Get-Location) $outputFolder
}
# Maak folder aan als deze niet bestaat
if (-not (Test-Path $outputFolder)) {
try {
New-Item -ItemType Directory -Path $outputFolder -Force | Out-Null
Write-Host "✓ Export folder aangemaakt: $outputFolder" -ForegroundColor Green
}
catch {
Write-Error "Kon export folder niet aanmaken: $($_.Exception.Message)"
return $null
}
}
else {
Write-Host "✓ Export folder bestaat: $outputFolder" -ForegroundColor Green
}
# Archiveer oude rapporten indien ingesteld
if ($Config.ExportSettings.ArchiveOldReports -and $Config.ExportSettings.MaxReportsToKeep -gt 0) {
try {
$existingReports = Get-ChildItem -Path $outputFolder -Filter "*PIM*Users*.csv" | Sort-Object CreationTime -Descending
$reportsToRemove = $existingReports | Select-Object -Skip $Config.ExportSettings.MaxReportsToKeep
foreach ($report in $reportsToRemove) {
Remove-Item $report.FullName -Force
Write-Host " - Oud rapport verwijderd: $($report.Name)" -ForegroundColor Gray
}
if ($reportsToRemove.Count -gt 0) {
Write-Host "✓ $($reportsToRemove.Count) oude rapporten gearchiveerd" -ForegroundColor Green
}
}
catch {
Write-Warning "Kon oude rapporten niet archiveren: $($_.Exception.Message)"
}
}
return $outputFolder
}
# Functie om verbinding te maken met Microsoft Graph
function Connect-MicrosoftGraph {
param(
[string]$ClientId,
[string]$ClientSecret,
[string]$TenantId
)
try {
Write-Host "Verbinding maken met Microsoft Graph voor tenant: $TenantId" -ForegroundColor Yellow
# Maak een credential object
$secureSecret = ConvertTo-SecureString $ClientSecret -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($ClientId, $secureSecret)
# Connect met Graph
Connect-MgGraph -ClientSecretCredential $credential -TenantId $TenantId -NoWelcome
Write-Host "✓ Succesvol verbonden met Microsoft Graph" -ForegroundColor Green
return $true
}
catch {
Write-Error "Fout bij verbinden met Microsoft Graph: $($_.Exception.Message)"
return $false
}
}
# Functie om groepsleden op te halen
function Get-GroupMembers {
param(
[string]$GroupId,
[string]$Customer,
[string]$GroupName,
[string]$RoleName,
[string]$AssignmentType,
[string]$AssignmentState,
[DateTime]$StartDateTime,
[DateTime]$EndDateTime
)
$groupMembers = @()
try {
Write-Host " - Ophalen leden van groep: $GroupName (rol: $RoleName)"
$members = Get-MgGroupMember -GroupId $GroupId -All -ErrorAction Stop
foreach ($member in $members) {
$memberInfo = Get-PrincipalInfo -PrincipalId $member.Id
$memberResult = [PSCustomObject]@{
Customer = $Customer
UserType = $memberInfo.UserType
DisplayName = $memberInfo.DisplayName
UserPrincipalName = $memberInfo.UserPrincipalName
Email = $memberInfo.Email
AccountEnabled = $memberInfo.AccountEnabled
CreatedDateTime = $memberInfo.CreatedDateTime
Department = $memberInfo.Department
JobTitle = $memberInfo.JobTitle
CompanyName = $memberInfo.CompanyName
PrincipalId = $member.Id
RoleName = $RoleName
AssignmentType = $AssignmentType
AssignmentState = $AssignmentState
StartDateTime = $StartDateTime
EndDateTime = $EndDateTime
ViaGroup = $GroupName
IsGroupMember = $true
}
# Skip als het lid zelf weer een groep is (om oneindige loops te voorkomen)
if ($memberResult.UserType -ne "Group") {
$groupMembers += $memberResult
}
}
Write-Host " └─ Gevonden $($groupMembers.Count) leden in groep $GroupName voor rol $RoleName"
}
catch {
Write-Warning "Kon groepsleden niet ophalen voor groep: $GroupId ($GroupName). Fout: $($_.Exception.Message)"
}
return $groupMembers
}
# Helper functie om gebruiker informatie op te halen
function Get-PrincipalInfo {
param(
[string]$PrincipalId
)
$result = @{
UserType = "Unknown"
DisplayName = "Unknown"
UserPrincipalName = "Unknown"
Email = "Unknown"
AccountEnabled = $null
CreatedDateTime = $null
Department = "Unknown"
JobTitle = "Unknown"
CompanyName = "Unknown"
}
if (-not $PrincipalId) {
return $result
}
try {
# Probeer als gebruiker
try {
$userDetails = Get-MgUser -UserId $PrincipalId -ErrorAction Stop
$result.UserType = "User"
$result.DisplayName = $userDetails.DisplayName
$result.UserPrincipalName = $userDetails.UserPrincipalName
$result.Email = $userDetails.Mail
$result.AccountEnabled = $userDetails.AccountEnabled
$result.CreatedDateTime = $userDetails.CreatedDateTime
$result.Department = $userDetails.Department
$result.JobTitle = $userDetails.JobTitle
$result.CompanyName = $userDetails.CompanyName
return $result
}
catch {
# Probeer als service principal
try {
$spDetails = Get-MgServicePrincipal -ServicePrincipalId $PrincipalId -ErrorAction Stop
$result.UserType = "ServicePrincipal"
$result.DisplayName = $spDetails.DisplayName
$result.UserPrincipalName = "SERVICE PRINCIPAL"
$result.Email = "N/A"
$result.AccountEnabled = $spDetails.AccountEnabled
$result.CreatedDateTime = $spDetails.CreatedDateTime
return $result
}
catch {
# Probeer als groep
try {
$groupDetails = Get-MgGroup -GroupId $PrincipalId -ErrorAction Stop
$result.UserType = "Group"
$result.DisplayName = $groupDetails.DisplayName
$result.UserPrincipalName = "GROUP"
$result.Email = $groupDetails.Mail
$result.AccountEnabled = $true
$result.CreatedDateTime = $groupDetails.CreatedDateTime
return $result
}
catch {
Write-Warning "Kon principal niet ophalen voor ID: $PrincipalId"
return $result
}
}
}
}
catch {
Write-Warning "Fout bij ophalen principal info voor $PrincipalId : $($_.Exception.Message)"
return $result
}
}
# Functie om PIM rol assignments op te halen
function Get-PIMRoleAssignments {
param(
[string]$TenantId,
[string]$CustomerName
)
$allPIMAssignments = @()
try {
Write-Host "Ophalen van PIM rol-toewijzingen voor $CustomerName..." -ForegroundColor Yellow
# Haal alle eligible role assignments op (PIM candidates)
Write-Host " - Ophalen van eligible assignments..." -ForegroundColor Cyan
try {
$eligibleAssignments = Get-MgRoleManagementDirectoryRoleEligibilitySchedule -All -ErrorAction SilentlyContinue
foreach ($assignment in $eligibleAssignments) {
try {
# Haal rol informatie op
$roleDefinition = Get-MgRoleManagementDirectoryRoleDefinition -UnifiedRoleDefinitionId $assignment.RoleDefinitionId -ErrorAction SilentlyContinue
if (-not $roleDefinition) { continue }
# Haal gebruiker informatie op
$principalInfo = Get-PrincipalInfo -PrincipalId $assignment.PrincipalId
$pimInfo = [PSCustomObject]@{
Customer = $CustomerName
TenantId = $TenantId
UserPrincipalName = $principalInfo.UserPrincipalName
DisplayName = $principalInfo.DisplayName
PrincipalId = $assignment.PrincipalId
EmailAddress = $principalInfo.Email
UserType = $principalInfo.UserType
RoleName = $roleDefinition.DisplayName
RoleId = $roleDefinition.Id
RoleTemplateId = $roleDefinition.TemplateId
AssignmentType = "Eligible"
Status = $assignment.Status
CreatedDateTime = $assignment.CreatedDateTime
StartDateTime = $assignment.ScheduleInfo.StartDateTime
EndDateTime = $assignment.ScheduleInfo.Expiration.EndDateTime
DirectoryScope = $assignment.DirectoryScopeId
AssignmentId = $assignment.Id
AccountEnabled = $principalInfo.AccountEnabled
Department = $principalInfo.Department
JobTitle = $principalInfo.JobTitle
CompanyName = $principalInfo.CompanyName
IsPIMManaged = $true
ViaGroup = "N/A"
IsGroupMember = $false
}
$allPIMAssignments += $pimInfo
# Als dit een groep is, haal dan ook de leden op
if ($principalInfo.UserType -eq "Group") {
$startDate = if ($assignment.ScheduleInfo.StartDateTime) { $assignment.ScheduleInfo.StartDateTime } else { [DateTime]::MinValue }
$endDate = if ($assignment.ScheduleInfo.Expiration.EndDateTime) { $assignment.ScheduleInfo.Expiration.EndDateTime } else { [DateTime]::MaxValue }
$groupMembers = Get-GroupMembers -GroupId $assignment.PrincipalId -Customer $CustomerName -GroupName $principalInfo.DisplayName -RoleName $roleDefinition.DisplayName -AssignmentType "Eligible" -AssignmentState $assignment.Status -StartDateTime $startDate -EndDateTime $endDate
foreach ($member in $groupMembers) {
$memberPimInfo = [PSCustomObject]@{
Customer = $member.Customer
TenantId = $TenantId
UserPrincipalName = $member.UserPrincipalName
DisplayName = $member.DisplayName
PrincipalId = $member.PrincipalId
EmailAddress = $member.Email
UserType = $member.UserType
RoleName = $member.RoleName
RoleId = $roleDefinition.Id
RoleTemplateId = $roleDefinition.TemplateId
AssignmentType = $member.AssignmentType
Status = $assignment.Status
CreatedDateTime = $assignment.CreatedDateTime
StartDateTime = $member.StartDateTime
EndDateTime = $member.EndDateTime
DirectoryScope = $assignment.DirectoryScopeId
AssignmentId = $assignment.Id + "_member_" + $member.PrincipalId
AccountEnabled = $member.AccountEnabled
Department = $member.Department
JobTitle = $member.JobTitle
CompanyName = $member.CompanyName
IsPIMManaged = $true
ViaGroup = $member.ViaGroup
IsGroupMember = $member.IsGroupMember
}
$allPIMAssignments += $memberPimInfo
}
}
}
catch {
Write-Warning "Fout bij verwerken van eligible assignment: $($_.Exception.Message)"
}
}
}
catch {
Write-Warning "Kon eligible assignments niet ophalen: $($_.Exception.Message)"
}
# Haal alle active role assignments op (permanent assignments via PIM)
Write-Host " - Ophalen van active assignments..." -ForegroundColor Cyan
try {
$activeAssignments = Get-MgRoleManagementDirectoryRoleAssignmentSchedule -All -ErrorAction SilentlyContinue
foreach ($assignment in $activeAssignments) {
try {
# Haal rol informatie op
$roleDefinition = Get-MgRoleManagementDirectoryRoleDefinition -UnifiedRoleDefinitionId $assignment.RoleDefinitionId -ErrorAction SilentlyContinue
if (-not $roleDefinition) { continue }
# Haal gebruiker informatie op
$principalInfo = Get-PrincipalInfo -PrincipalId $assignment.PrincipalId
# Bepaal of dit een permanente of tijdelijke (PIM) active assignment is
$assignmentType = "Active"
$isPermanent = $false
# Als er geen eindtijd is of eindtijd is ver in de toekomst (> 1 jaar), dan is het permanent
$endDateTime = $assignment.ScheduleInfo.Expiration.EndDateTime
if (-not $endDateTime -or
[string]::IsNullOrEmpty($endDateTime) -or
$endDateTime -gt (Get-Date).AddYears(1)) {
$assignmentType = "Permanent"
$isPermanent = $true
}
$pimInfo = [PSCustomObject]@{
Customer = $CustomerName
TenantId = $TenantId
UserPrincipalName = $principalInfo.UserPrincipalName
DisplayName = $principalInfo.DisplayName
PrincipalId = $assignment.PrincipalId
EmailAddress = $principalInfo.Email
UserType = $principalInfo.UserType
RoleName = $roleDefinition.DisplayName
RoleId = $roleDefinition.Id
RoleTemplateId = $roleDefinition.TemplateId
AssignmentType = $assignmentType
Status = $assignment.Status
CreatedDateTime = $assignment.CreatedDateTime
StartDateTime = $assignment.ScheduleInfo.StartDateTime
EndDateTime = if ($isPermanent) { "Never" } else { $assignment.ScheduleInfo.Expiration.EndDateTime }
DirectoryScope = $assignment.DirectoryScopeId
AssignmentId = $assignment.Id
AccountEnabled = $principalInfo.AccountEnabled
Department = $principalInfo.Department
JobTitle = $principalInfo.JobTitle
CompanyName = $principalInfo.CompanyName
IsPIMManaged = if ($isPermanent) { $false } else { $true }
ViaGroup = "N/A"
IsGroupMember = $false
}
$allPIMAssignments += $pimInfo
# Als dit een groep is, haal dan ook de leden op
if ($principalInfo.UserType -eq "Group") {
$startDate = if ($assignment.ScheduleInfo.StartDateTime) { $assignment.ScheduleInfo.StartDateTime } else { [DateTime]::MinValue }
$endDate = if ($isPermanent) { [DateTime]::MaxValue } else {
if ($assignment.ScheduleInfo.Expiration.EndDateTime) { $assignment.ScheduleInfo.Expiration.EndDateTime } else { [DateTime]::MaxValue }
}
$groupMembers = Get-GroupMembers -GroupId $assignment.PrincipalId -Customer $CustomerName -GroupName $principalInfo.DisplayName -RoleName $roleDefinition.DisplayName -AssignmentType $assignmentType -AssignmentState $assignment.Status -StartDateTime $startDate -EndDateTime $endDate
foreach ($member in $groupMembers) {
$memberPimInfo = [PSCustomObject]@{
Customer = $member.Customer
TenantId = $TenantId
UserPrincipalName = $member.UserPrincipalName
DisplayName = $member.DisplayName
PrincipalId = $member.PrincipalId
EmailAddress = $member.Email
UserType = $member.UserType
RoleName = $member.RoleName
RoleId = $roleDefinition.Id
RoleTemplateId = $roleDefinition.TemplateId
AssignmentType = $member.AssignmentType
Status = $assignment.Status
CreatedDateTime = $assignment.CreatedDateTime
StartDateTime = $member.StartDateTime
EndDateTime = $member.EndDateTime
DirectoryScope = $assignment.DirectoryScopeId
AssignmentId = $assignment.Id + "_member_" + $member.PrincipalId
AccountEnabled = $member.AccountEnabled
Department = $member.Department
JobTitle = $member.JobTitle
CompanyName = $member.CompanyName
IsPIMManaged = if ($member.AssignmentType -eq "Permanent") { $false } else { $true }
ViaGroup = $member.ViaGroup
IsGroupMember = $member.IsGroupMember
}
$allPIMAssignments += $memberPimInfo
}
}
}
catch {
Write-Warning "Fout bij verwerken van active assignment: $($_.Exception.Message)"
}
}
}
catch {
Write-Warning "Kon active assignments niet ophalen: $($_.Exception.Message)"
}
Write-Host "✓ Gevonden $($allPIMAssignments.Count) PIM rol-toewijzingen voor $CustomerName" -ForegroundColor Green
return $allPIMAssignments
}
catch {
Write-Error "Fout bij ophalen PIM rol-toewijzingen voor $CustomerName : $($_.Exception.Message)"
return @()
}
}
# Functie om permanente (non-PIM) rol assignments op te halen
# Functie om permanente (non-PIM) rol assignments op te halen
function Get-PermanentRoleAssignments {
param(
[string]$TenantId,
[string]$CustomerName
)
$allPermanentAssignments = @()
try {
Write-Host "Ophalen van klassieke (non-PIM) rol-toewijzingen voor $CustomerName..." -ForegroundColor Yellow
Write-Host " (Permanente rollen zonder eindtijd worden al gedetecteerd in PIM Active assignments)" -ForegroundColor Gray
# Method 1: Haal klassieke directory role assignments op (alleen als ze NIET in PIM zitten)
Write-Host " - Ophalen van klassieke directory role assignments..." -ForegroundColor Cyan
try {
$directoryRoleAssignments = Get-MgRoleManagementDirectoryRoleAssignment -All -ErrorAction SilentlyContinue
Write-Host " - Gevonden $($directoryRoleAssignments.Count) directory role assignments" -ForegroundColor DarkCyan
foreach ($assignment in $directoryRoleAssignments) {
try {
# Haal rol informatie op
$roleDefinition = Get-MgRoleManagementDirectoryRoleDefinition -UnifiedRoleDefinitionId $assignment.RoleDefinitionId -ErrorAction SilentlyContinue
if (-not $roleDefinition) { continue }
# Check of dit assignment AL via PIM loopt (dus NIET klassiek permanent)
$isPIMManaged = $false
try {
# Kijk of er PIM eligible schedules zijn
$pimEligible = Get-MgRoleManagementDirectoryRoleEligibilitySchedule -Filter "principalId eq '$($assignment.PrincipalId)' and roleDefinitionId eq '$($assignment.RoleDefinitionId)'" -ErrorAction SilentlyContinue
# Kijk of er PIM assignment schedules zijn (ook permanente)
$pimAssignment = Get-MgRoleManagementDirectoryRoleAssignmentSchedule -Filter "principalId eq '$($assignment.PrincipalId)' and roleDefinitionId eq '$($assignment.RoleDefinitionId)'" -ErrorAction SilentlyContinue
if (($pimEligible | Measure-Object).Count -gt 0 -or ($pimAssignment | Measure-Object).Count -gt 0) {
$isPIMManaged = $true
}
}
catch {
$isPIMManaged = $false
}
# Alleen verwerken als het NIET PIM-managed is (dus ouderwetse klassieke assignment)
if (-not $isPIMManaged) {
Write-Host " - Klassieke permanente rol gevonden: $($roleDefinition.DisplayName) voor principal $($assignment.PrincipalId)" -ForegroundColor Green
# Haal gebruiker/principal informatie op
$principalInfo = Get-PrincipalInfo -PrincipalId $assignment.PrincipalId
$permanentInfo = [PSCustomObject]@{
Customer = $CustomerName
TenantId = $TenantId
UserPrincipalName = $principalInfo.UserPrincipalName
DisplayName = $principalInfo.DisplayName
PrincipalId = $assignment.PrincipalId
EmailAddress = $principalInfo.Email
UserType = $principalInfo.UserType
RoleName = $roleDefinition.DisplayName
RoleId = $roleDefinition.Id
RoleTemplateId = $roleDefinition.TemplateId
AssignmentType = "Permanent"
Status = "Active"
CreatedDateTime = $principalInfo.CreatedDateTime
StartDateTime = "N/A"
EndDateTime = "Never"
DirectoryScope = $assignment.DirectoryScopeId
AssignmentId = $assignment.Id
AccountEnabled = $principalInfo.AccountEnabled
Department = $principalInfo.Department
JobTitle = $principalInfo.JobTitle
CompanyName = $principalInfo.CompanyName
IsPIMManaged = $false
ViaGroup = "N/A"
IsGroupMember = $false
}
$allPermanentAssignments += $permanentInfo
# Als dit een groep is, haal dan ook de leden op
if ($principalInfo.UserType -eq "Group") {
$groupMembers = Get-GroupMembers -GroupId $assignment.PrincipalId -Customer $CustomerName -GroupName $principalInfo.DisplayName -RoleName $roleDefinition.DisplayName -AssignmentType "Permanent" -AssignmentState "Active" -StartDateTime ([DateTime]::MinValue) -EndDateTime ([DateTime]::MaxValue)
foreach ($groupMember in $groupMembers) {
$memberPermanentInfo = [PSCustomObject]@{
Customer = $groupMember.Customer
TenantId = $TenantId
UserPrincipalName = $groupMember.UserPrincipalName
DisplayName = $groupMember.DisplayName
PrincipalId = $groupMember.PrincipalId
EmailAddress = $groupMember.Email
UserType = $groupMember.UserType
RoleName = $groupMember.RoleName
RoleId = $roleDefinition.Id
RoleTemplateId = $roleDefinition.TemplateId
AssignmentType = $groupMember.AssignmentType
Status = "Active"
CreatedDateTime = $groupMember.CreatedDateTime
StartDateTime = "N/A"
EndDateTime = "Never"
DirectoryScope = $assignment.DirectoryScopeId
AssignmentId = $assignment.Id + "_member_" + $groupMember.PrincipalId
AccountEnabled = $groupMember.AccountEnabled
Department = $groupMember.Department
JobTitle = $groupMember.JobTitle
CompanyName = $groupMember.CompanyName
IsPIMManaged = $false
ViaGroup = $groupMember.ViaGroup
IsGroupMember = $groupMember.IsGroupMember
}
$allPermanentAssignments += $memberPermanentInfo
}
}
}
}
catch {
Write-Warning "Fout bij verwerken van klassiek assignment: $($_.Exception.Message)"
}
}
}
catch {
Write-Warning "Kon klassieke role assignments niet ophalen: $($_.Exception.Message)"
}
Write-Host "✓ Gevonden $($allPermanentAssignments.Count) permanente rol-toewijzingen voor $CustomerName" -ForegroundColor Green
return $allPermanentAssignments
}
catch {
Write-Error "Fout bij ophalen permanente rol-toewijzingen voor $CustomerName : $($_.Exception.Message)"
return @()
}
}
# Functie om wijzigingen te detecteren tussen exports
function Compare-PIMExports {
param(
[array]$CurrentResults,
[string]$ExportPath,
[string]$DatePrefix
)
$changes = @()
try {
Write-Host "Detecteren van wijzigingen ten opzichte van vorige export..." -ForegroundColor Yellow
Write-Host " - Normale PIM activaties (Eligible <-> Active) worden niet getoond als wijzigingen" -ForegroundColor Gray
# Zoek naar vorige export bestanden (oudere datums dan huidige)
$allFiles = Get-ChildItem -Path $ExportPath -Filter "*_All_Customers_Full_Report.csv" |
Where-Object { $_.Name -notlike "$DatePrefix*" }
if ($allFiles.Count -eq 0) {
Write-Host " - Geen vorige export gevonden. Dit is waarschijnlijk de eerste run." -ForegroundColor Gray
return @()
}
# Sorteer op datum in bestandsnaam (nieuwste eerst)
$previousFiles = $allFiles | Sort-Object {
# Extract datum uit bestandsnaam (YYYYMMDD)
if ($_.Name -match '^(\d{8})_') {
[datetime]::ParseExact($matches[1], 'yyyyMMdd', $null)
} else {
$_.CreationTime
}
} -Descending | Select-Object -First 1
$previousFile = $previousFiles.FullName
Write-Host " - Vorige export gevonden: $($previousFiles.Name)" -ForegroundColor Cyan
# Lees vorige export
try {
$previousResults = Import-Csv -Path $previousFile -ErrorAction Stop
Write-Host " - Vorige export geladen: $($previousResults.Count) records" -ForegroundColor Green
}
catch {
Write-Warning "Kon vorige export niet laden: $($_.Exception.Message)"
return @()
}
# Maak unieke identifiers voor vergelijking
Write-Host " - Analyseren van wijzigingen..." -ForegroundColor Cyan
# Huidige data voorbereiden
$currentLookup = @{}
foreach ($record in $CurrentResults) {
$key = "$($record.Customer)_$($record.PrincipalId)_$($record.RoleName)"
$currentLookup[$key] = $record
}
# Vorige data voorbereiden
$previousLookup = @{}
foreach ($record in $previousResults) {
$key = "$($record.Customer)_$($record.PrincipalId)_$($record.RoleName)"
$previousLookup[$key] = $record
}
# Detecteer nieuwe assignments
foreach ($key in $currentLookup.Keys) {
if (-not $previousLookup.ContainsKey($key)) {
$record = $currentLookup[$key]
$change = [PSCustomObject]@{
ChangeType = "NEW"
Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Customer = $record.Customer
DisplayName = $record.DisplayName
UserPrincipalName = $record.UserPrincipalName
RoleName = $record.RoleName
AssignmentType = $record.AssignmentType
UserType = $record.UserType
PreviousValue = "N/A"
CurrentValue = "$($record.AssignmentType)"
Description = "Nieuwe rol toewijzing gedetecteerd"
PrincipalId = $record.PrincipalId
}
$changes += $change
}
}
# Detecteer verwijderde assignments
foreach ($key in $previousLookup.Keys) {
if (-not $currentLookup.ContainsKey($key)) {
$record = $previousLookup[$key]
$change = [PSCustomObject]@{
ChangeType = "REMOVED"
Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Customer = $record.Customer
DisplayName = $record.DisplayName
UserPrincipalName = $record.UserPrincipalName
RoleName = $record.RoleName
AssignmentType = $record.AssignmentType
UserType = $record.UserType
PreviousValue = "$($record.AssignmentType)"
CurrentValue = "N/A"
Description = "Rol toewijzing verwijderd"
PrincipalId = $record.PrincipalId
}
$changes += $change
}
}
# Detecteer gewijzigde assignment types (exclusief normale PIM activaties/deactivaties)
foreach ($key in $currentLookup.Keys) {
if ($previousLookup.ContainsKey($key)) {
$current = $currentLookup[$key]
$previous = $previousLookup[$key]
if ($current.AssignmentType -ne $previous.AssignmentType) {
# Skip normale PIM activaties/deactivaties (Eligible <-> Active)
$isPIMActivation = ($previous.AssignmentType -eq "Eligible" -and $current.AssignmentType -eq "Active") -or
($previous.AssignmentType -eq "Active" -and $current.AssignmentType -eq "Eligible")
if (-not $isPIMActivation) {
$change = [PSCustomObject]@{
ChangeType = "MODIFIED"
Timestamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
Customer = $current.Customer
DisplayName = $current.DisplayName
UserPrincipalName = $current.UserPrincipalName
RoleName = $current.RoleName
AssignmentType = $current.AssignmentType
UserType = $current.UserType
PreviousValue = $previous.AssignmentType
CurrentValue = $current.AssignmentType
Description = "Assignment type structureel gewijzigd van $($previous.AssignmentType) naar $($current.AssignmentType)"
PrincipalId = $current.PrincipalId
}
$changes += $change
}
}
}
}
# Rapporteer resultaten
$newCount = ($changes | Where-Object { $_.ChangeType -eq "NEW" }).Count
$removedCount = ($changes | Where-Object { $_.ChangeType -eq "REMOVED" }).Count
$modifiedCount = ($changes | Where-Object { $_.ChangeType -eq "MODIFIED" }).Count
Write-Host "✓ Wijzigingsanalyse voltooid:" -ForegroundColor Green
Write-Host " - Nieuwe toewijzingen: $newCount" -ForegroundColor Green
Write-Host " - Verwijderde toewijzingen: $removedCount" -ForegroundColor Red
Write-Host " - Gewijzigde toewijzingen: $modifiedCount" -ForegroundColor Yellow
# Exporteer wijzigingen naar CSV
if ($changes.Count -gt 0) {
$changesPath = Join-Path $ExportPath "${DatePrefix}_Changes_Report.csv"
$changes | Export-Csv -Path $changesPath -NoTypeInformation -Encoding UTF8
Write-Host "✓ Wijzigingen rapport opgeslagen: $changesPath" -ForegroundColor Green
}
return $changes
}
catch {
Write-Error "Fout bij wijzigingsdetectie: $($_.Exception.Message)"
return @()
}
}
# Functie om HTML dashboard te genereren
function New-HTMLDashboard {
param(
[array]$AllResults,
[string]$ExportPath,
[string]$DatePrefix,
[hashtable]$Config,
[array]$Changes = @()
)
try {
Write-Host " - Voorbereiden HTML data..." -ForegroundColor Cyan
# Groepeer data per klant
$customerGroups = $AllResults | Group-Object Customer
# Wijzigingen statistieken (altijd tonen, ook bij 0)
$newChanges = ($Changes | Where-Object { $_.ChangeType -eq "NEW" }).Count
$removedChanges = ($Changes | Where-Object { $_.ChangeType -eq "REMOVED" }).Count
$modifiedChanges = ($Changes | Where-Object { $_.ChangeType -eq "MODIFIED" }).Count
$changesStats = @"
<div class="stat-card changes-new">
<h4>Nieuwe Toewijzingen</h4>
<div class="stat-number">$newChanges</div>
</div>
<div class="stat-card changes-removed">
<h4>Verwijderde Toewijzingen</h4>
<div class="stat-number">$removedChanges</div>
</div>
<div class="stat-card changes-modified">
<h4>Gewijzigde Toewijzingen</h4>
<div class="stat-number">$modifiedChanges</div>
</div>
"@
# Wijzigingen tab (altijd tonen)
$changesTab = '<button class="tablinks" onclick="showChanges(event)"><i class="fa-solid fa-exchange-alt"></i> Wijzigingen</button>'
# Bouw wijzigingen tabel
$changesTableRows = ""
foreach ($change in $Changes) {
$changeTypeColor = switch ($change.ChangeType) {
"NEW" { "color: #28a745; font-weight: bold;" }
"REMOVED" { "color: #dc3545; font-weight: bold;" }
"MODIFIED" { "color: #ffc107; font-weight: bold;" }
default { "" }
}
$changeIcon = switch ($change.ChangeType) {
"NEW" { "fa-plus-circle" }
"REMOVED" { "fa-minus-circle" }
"MODIFIED" { "fa-edit" }
default { "fa-question-circle" }
}
$changesTableRows += @"
<tr>
<td><i class="fa-solid $changeIcon" style="$changeTypeColor"></i> <span style="$changeTypeColor">$($change.ChangeType)</span></td>
<td>$($change.Timestamp)</td>
<td>$($change.Customer)</td>
<td>$($change.DisplayName)</td>
<td>$($change.UserPrincipalName)</td>
<td>$($change.RoleName)</td>
<td>$($change.PreviousValue)</td>
<td>$($change.CurrentValue)</td>
<td>$($change.Description)</td>
</tr>
"@
}
# Wijzigingen content (altijd tonen)
$changesTableRows = ""
$noChangesMessage = ""
if ($Changes.Count -gt 0) {
# Bouw wijzigingen tabel
foreach ($change in $Changes) {
$changeTypeColor = switch ($change.ChangeType) {
"NEW" { "color: #28a745; font-weight: bold;" }
"REMOVED" { "color: #dc3545; font-weight: bold;" }
"MODIFIED" { "color: #ffc107; font-weight: bold;" }
default { "" }
}
$changeIcon = switch ($change.ChangeType) {
"NEW" { "fa-plus-circle" }
"REMOVED" { "fa-minus-circle" }
"MODIFIED" { "fa-edit" }
default { "fa-question-circle" }
}
$changesTableRows += @"
<tr>
<td><i class="fa-solid $changeIcon" style="$changeTypeColor"></i> <span style="$changeTypeColor">$($change.ChangeType)</span></td>
<td>$($change.Timestamp)</td>
<td>$($change.Customer)</td>
<td>$($change.DisplayName)</td>
<td>$($change.UserPrincipalName)</td>
<td>$($change.RoleName)</td>
<td>$($change.PreviousValue)</td>
<td>$($change.CurrentValue)</td>
<td>$($change.Description)</td>
</tr>
"@
}
} else {
$noChangesMessage = @"
<div style="text-align: center; padding: 40px; color: #6c757d; background: #f8f9fa; border-radius: 8px; margin: 20px 0;">
<i class="fa-solid fa-check-circle" style="font-size: 48px; color: #28a745; margin-bottom: 15px;"></i>
<h4 style="margin: 0 0 10px 0; color: #495057;">Geen wijzigingen gedetecteerd</h4>
<p style="margin: 0; font-size: 16px;">Alle rol-toewijzingen zijn hetzelfde gebleven sinds de vorige export.</p>
</div>
"@
}
$changesContent = @"
<div id="Changes" class="tabcontent">
<h3><i class="fa-solid fa-exchange-alt"></i> Wijzigingen sinds vorige export</h3>
<div class="stats-grid">
<div class="stat-card changes-new">
<h4>Nieuwe Toewijzingen</h4>
<div class="stat-number">$(($Changes | Where-Object { $_.ChangeType -eq "NEW" }).Count)</div>