-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathDeploy-TierModel.ps1
More file actions
2613 lines (2322 loc) · 132 KB
/
Copy pathDeploy-TierModel.ps1
File metadata and controls
2613 lines (2322 loc) · 132 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
Modular TierModel deployment using dedicated cmdlets per entity type.
.DESCRIPTION
Performs TierModel component deployment including organizational units, groups, users,
GPOs, OU ACL delegations, and ADMX configurations. Uses modular cmdlet architecture
for improved maintainability and testing. Supports planning mode (default) and
execution mode (with -ConfirmApply).
.PARAMETER PreferredDc
The preferred domain controller to use for all Active Directory operations.
Must be accessible and have appropriate permissions for creating AD objects.
.PARAMETER OuOnly
Deploy only organizational units. When specified, only OU creation and
configuration will be performed based on TierModel specification.
.PARAMETER GroupOnly
Deploy only security groups. When specified, only group creation and
membership configuration will be performed. (Not yet implemented in v0.2)
.PARAMETER UserOnly
Deploy only user accounts. When specified, only user account creation
and configuration will be performed. (Not yet implemented in v0.2)
.PARAMETER GposOnly
Deploy only Group Policy Objects. When specified, only GPO creation,
configuration, and linking will be performed. (Not yet implemented in v0.2)
.PARAMETER OuAclsOnly
Deploy only OU ACL delegations. When specified, only organizational unit
access control list delegations will be applied. (Not yet implemented in v0.2)
.PARAMETER AdmxOnly
Deploy only ADMX template configurations. When specified, only administrative
template imports and configurations will be applied. (Not yet implemented in v0.2)
.PARAMETER FullDeployment
Perform comprehensive deployment of all TierModel components in dependency order:
OUs -> Groups -> Users -> OU ACL Delegations -> GPOs -> ADMX.
Provides consolidated reporting at completion.
.PARAMETER ConfirmApply
Execute the deployment plan. Without this switch, the script runs in planning
mode only, showing what changes would be made without applying them.
.PARAMETER Logging
Enable detailed logging to files. When specified, deployment operations and
results will be logged to files in the LogPath directory (or current directory).
.PARAMETER LogPath
Directory path where log files will be created when Logging is enabled.
If not provided, logs are created in the current directory. Directory will be
created automatically if it doesn't exist.
.PARAMETER OutputFileBase
Base filename for generated deployment reports and logs (without extension or timestamp).
The actual filename will include a timestamp and appropriate extension.
Used when Logging is enabled or when generating deployment reports.
.EXAMPLE
.\Deploy-TierModel.ps1 -PreferredDc "DC01.contoso.com" -OuOnly
Generate deployment plan for organizational units only (planning mode).
.EXAMPLE
.\Deploy-TierModel.ps1 -PreferredDc "DC01.contoso.com" -OuOnly -ConfirmApply -Logging -LogPath "C:\Logs"
Deploy organizational units and log all operations to C:\Logs directory.
.EXAMPLE
.\Deploy-TierModel.ps1 -PreferredDc "DC01.contoso.com" -FullDeployment -ConfirmApply -Logging -OutputFileBase "TierModel-Deploy"
Perform full TierModel deployment with logging enabled using custom log filename base.
.NOTES
Version: 2.0
Requires: TierModel PowerShell module, appropriate Active Directory permissions
#>
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)]
[string]$PreferredDc,
[switch]$OuOnly,
[switch]$GroupOnly,
[switch]$UserOnly,
[switch]$GposOnly,
[switch]$OuAclsOnly,
[switch]$AdmxOnly,
[switch]$FullDeployment,
[switch]$ConfirmApply,
[switch]$IncludeMsa,
[switch]$IncludeGmsa,
[switch]$IncludeDmsa,
[switch]$IncludeWinLaps,
[Parameter()]
[string]$AdmlLanguage = 'en-US',
[Parameter()]
[switch]$Logging,
[Parameter()]
[string]$LogPath,
[Parameter()]
[string]$OutputFileBase
)
Set-StrictMode -Version Latest
$ErrorActionPreference = 'Stop'
# Validate that only one deployment scope parameter is specified
$scopeParameters = @($OuOnly, $GroupOnly, $UserOnly, $GposOnly, $OuAclsOnly, $AdmxOnly, $FullDeployment)
$activeScopeCount = @($scopeParameters | Where-Object { $_ }).Count
$includeParameters = @($IncludeMsa, $IncludeGmsa, $IncludeDmsa, $IncludeWinLaps)
$activeIncludeCount = @($includeParameters | Where-Object { $_ }).Count
if ($activeScopeCount -eq 0 -and $activeIncludeCount -eq 0) {
Write-Error "You must specify exactly one deployment scope parameter (-OuOnly, -GroupOnly, -UserOnly, -GposOnly, -OuAclsOnly, -AdmxOnly, -FullDeployment) or one or more -Include* switches (-IncludeMsa, -IncludeGmsa, -IncludeDmsa, -IncludeWinLaps)." -ErrorAction Stop
}
elseif ($activeScopeCount -gt 1) {
Write-Error "You can only specify one deployment scope parameter at a time. Cannot combine -OuOnly, -GroupOnly, -UserOnly, -GposOnly, -OuAclsOnly, -AdmxOnly, and -FullDeployment" -ErrorAction Stop
}
elseif ($activeIncludeCount -gt 0 -and $activeScopeCount -eq 1 -and -not $FullDeployment) {
Write-Error "-IncludeMsa, -IncludeGmsa, -IncludeDmsa, and -IncludeWinLaps can only be used standalone or combined with -FullDeployment. They cannot be used with -OuOnly, -GroupOnly, -UserOnly, -GposOnly, -OuAclsOnly, or -AdmxOnly." -ErrorAction Stop
}
Write-Host "Deploy TierModel orchestration starting." -ForegroundColor Cyan
Write-Host "Preferred DC: $PreferredDc" -ForegroundColor DarkCyan
# Validate logging parameters and prompt if needed
if ($Logging -and -not $OutputFileBase) {
$OutputFileBase = Read-Host "Enter base filename for logs (timestamp and extension will be added automatically)"
if ([string]::IsNullOrWhiteSpace($OutputFileBase)) {
throw "OutputFileBase cannot be empty when Logging is enabled"
}
}
# Initialize logging if requested
if ($Logging) {
$timestamp = Get-Date -Format 'MMddyy-HHmm'
$logFileName = "$OutputFileBase-$timestamp.log"
# Use LogPath directory if provided, otherwise use current directory
if ($LogPath) {
# Ensure the directory exists
if (-not (Test-Path $LogPath)) {
New-Item -Path $LogPath -ItemType Directory -Force | Out-Null
Write-Host "Created log directory: $LogPath" -ForegroundColor Gray
}
$script:LogFilePath = Join-Path $LogPath $logFileName
} else {
# Use current working directory
$script:LogFilePath = Join-Path (Get-Location) $logFileName
}
Write-Host "Logging enabled: $script:LogFilePath" -ForegroundColor Gray
# Initialize log file with header - Write-TierModelLog will handle file creation
# Just ensure the file path is valid by testing the directory
$logDir = Split-Path $script:LogFilePath -Parent
if (-not (Test-Path $logDir)) {
New-Item -Path $logDir -ItemType Directory -Force | Out-Null
}
}
# Check PowerShell version before importing the module
function Write-TierModelFailFast {
<#
.SYNOPSIS
Renders a consistent fail-fast prerequisite message and closing line.
.DESCRIPTION
Produces the standard fail-fast layout used by every up-front gate: a blank line, the
indented message line(s) in red, an optional "Remediation steps:" block in yellow
(blank-line separated), and the closing "Deploy script completed." line — so all
fail-fast paths (PowerShell version, dMSA DFL, and the general prerequisite check) look
identical.
#>
param(
[Parameter(Mandatory)][AllowEmptyCollection()][string[]]$Message,
[AllowEmptyCollection()][string[]]$Remediation = @()
)
Write-Host ""
foreach ($line in $Message) { Write-Host " $line" -ForegroundColor Red }
if (@($Remediation).Count -gt 0) {
Write-Host ""
Write-Host "Remediation steps:" -ForegroundColor Yellow
foreach ($line in $Remediation) { Write-Host " - $line" -ForegroundColor Yellow }
}
Write-Host ""
Write-Host "Deploy script completed." -ForegroundColor Green
}
if ($PSVersionTable.PSVersion.Major -lt 7) {
Write-TierModelFailFast -Message @(
"Deploying and Auditing of the Tier Model requires PowerShell 7.x or later.",
"Current version: PowerShell $($PSVersionTable.PSVersion)"
) -Remediation @(
"Run the Tier Model from a PowerShell 7 (pwsh) console. If PowerShell 7 is not installed, obtain it from https://aka.ms/powershell."
)
return
}
# Import TierModel module with all public functions
Import-Module (Join-Path $PSScriptRoot 'Modules\TierModel\TierModel.psd1') -Force -Verbose:$false
Write-Host "TierModel module loaded successfully." -ForegroundColor Green
# ── Critical pre-flight gate: dMSA Domain Functional Level ───────────────────────
# dMSA delegation (-IncludeDmsa) has a hard dependency on a Domain Functional Level of
# Windows Server 2025 — the dMSA schema attributes do not exist below DFL 2025. Like the
# PowerShell-version gate above, fail fast here with a clean message BEFORE running any
# further prerequisite sub-checks or deployment phases, rather than letting the dMSA ACL
# planner surface a confusing "attribute not found in schema" error deep in the run.
# Only gate on a DFL we actually read; if the query fails (e.g. DC unreachable) fall through
# to the standard prerequisite validation below, which reports connectivity problems properly.
if ($IncludeDmsa) {
$dmsaDfl = $null
try {
$dmsaDomain = Get-ADDomain -Server $PreferredDc -ErrorAction Stop
if ($dmsaDomain -and $dmsaDomain.PSObject.Properties['DomainMode']) {
$dmsaDfl = [string]$dmsaDomain.DomainMode
}
} catch { }
if ($dmsaDfl -and $dmsaDfl -ne 'Windows2025Domain') {
$dmsaDflFriendly = (($dmsaDfl -replace 'Windows(\d{4})(R2)?Domain', 'Windows Server $1 $2') -replace '\s+', ' ').Trim()
Write-TierModelFailFast -Message @(
"dMSA delegation (-IncludeDmsa) requires a Domain Functional Level of Windows Server 2025.",
"Current Domain Functional Level: $dmsaDflFriendly"
) -Remediation @(
"Ensure all Domain Controllers in this forest are Server 2025 OS, then increase the DFL to 2025, follow all Microsoft guidance."
)
return
}
}
# Confirmation prompt for ConfirmApply to prevent accidental execution
if ($ConfirmApply) {
Write-Host ""
Write-Host "WARNING: You are about to execute Active Directory changes!" -ForegroundColor Yellow
Write-Host "These changes, while low risk, will modify your Active Directory environment." -ForegroundColor Yellow
Write-Host "Please confirm you want to proceed with execution." -ForegroundColor Yellow
Write-Host ""
$confirmation = Read-Host "Type 'Y' to continue with execution, any other key to cancel"
if ($confirmation -ne 'Y') {
Write-Host ""
Write-Host "Deployment cancelled by user." -ForegroundColor Red
Write-Host "Run without -ConfirmApply to see the deployment plan first." -ForegroundColor Cyan
exit 0
}
Write-Host ""
Write-Host "Proceeding with deployment execution..." -ForegroundColor Green
Write-Host ""
}
if ($Logging) {
# Initialize the log file with deployment start information
Write-TierModelLog -LogPath $script:LogFilePath -Level 'Info' -Message "TierModel deployment started" -Data @{
PreferredDc = $PreferredDc
Mode = if ($ConfirmApply) { 'EXECUTION' } else { 'PLANNING' }
Scope = if ($FullDeployment) { 'FullDeployment' } elseif ($OuOnly) { 'OuOnly' } elseif ($GroupOnly) { 'GroupOnly' } elseif ($UserOnly) { 'UserOnly' } elseif ($GposOnly) { 'GposOnly' } elseif ($OuAclsOnly) { 'OuAclsOnly' } elseif ($AdmxOnly) { 'AdmxOnly' } else { 'Unknown' }
Version = 'v0.2'
UserConfirmed = $ConfirmApply
}
Write-TierModelLog -LogPath $script:LogFilePath -Level 'Info' -Message "TierModel module loaded successfully"
}
# Validate prerequisites
Write-Host "Validating prerequisites..." -ForegroundColor Cyan
$depsPath = Join-Path $PSScriptRoot 'config\dependencies.json'
try {
$prereqSplat = @{ PreferredDc = $PreferredDc; DependenciesPath = $depsPath }
if ($IncludeMsa) { $prereqSplat['IncludeMsa'] = $true }
if ($IncludeGmsa) { $prereqSplat['IncludeGmsa'] = $true }
if ($IncludeDmsa) { $prereqSplat['IncludeDmsa'] = $true }
if ($IncludeWinLaps) { $prereqSplat['IncludeWinLaps'] = $true }
# Validate feature-specific prerequisites (gMSA KDS root key, Windows LAPS schema, dMSA
# schema/KDS, etc.) HERE, up front, so any unmet -Include prerequisite fails fast before
# a single deployment phase runs — rather than surfacing as a confusing planner error deep
# in a -FullDeployment run.
$prereqResult = Test-TierModelPrerequisites @prereqSplat
# Handle array results
if ($prereqResult -is [array] -and $prereqResult.Count -gt 0) {
$prereqResult = $prereqResult[0]
}
if (-not $prereqResult -or -not $prereqResult.PSObject.Properties['Valid'] -or -not $prereqResult.Valid) {
$ffMessages = @()
if ($prereqResult -and $prereqResult.Errors) { $ffMessages = @($prereqResult.Errors) }
if ($ffMessages.Count -eq 0) { $ffMessages = @('Prerequisites were not met.') }
$ffRemediation = @()
if ($prereqResult -and $prereqResult.Remediation) { $ffRemediation = @($prereqResult.Remediation) }
Write-TierModelFailFast -Message $ffMessages -Remediation $ffRemediation
exit 1
}
Write-Host "Prerequisites validation passed." -ForegroundColor Green
if ($Logging) {
Write-TierModelLog -LogPath $script:LogFilePath -Level 'Info' -Message "Prerequisites validation passed"
}
}
catch {
Write-Host "Error running prerequisites check: $($_.Exception.Message)" -ForegroundColor Red
if ($Logging) {
Write-TierModelLog -LogPath $script:LogFilePath -Level 'Error' -Message "Prerequisites check failed: $($_.Exception.Message)"
}
exit 1
}
# Load configuration
Write-Host "Loading configuration..." -ForegroundColor Cyan
try {
$config = Get-TierModelConfig
Write-Host "Configuration loaded successfully." -ForegroundColor Green
Write-Host "" # Blank line for spacing
if ($Logging) {
Write-TierModelLog -LogPath $script:LogFilePath -Level 'Info' -Message "Configuration loaded successfully"
}
} catch {
Write-Host "Failed to load configuration: $($_.Exception.Message)" -ForegroundColor Red
if ($Logging) {
Write-TierModelLog -LogPath $script:LogFilePath -Level 'Error' -Message "Failed to load configuration: $($_.Exception.Message)"
}
exit 1
}
# Planned orchestration pattern (placeholder):
# 1. Always: Load config via Get-TierModelConfig
# 2. For each scope-only (e.g. -OuOnly): Call Get-TierModelOu for plan
# If -ConfirmApply also supplied: Call New-TierModelOu then summarize results
# 3. FullDeployment: Sequence all Get-* then conditionally New-* respecting dependencies
# Order target: OU -> Groups -> Users -> OU ACL Delegations -> GPOs -> ADMX
# 4. Reporting: Aggregate per-entity plan/changes into unified deployment summary
function Invoke-OuDeployment {
param(
[Parameter(Mandatory)] [object]$Config,
[Parameter(Mandatory)] [string]$DomainController,
[switch]$Apply,
[switch]$Silent # For FullDeployment - suppress progress output, return data only
)
if (-not $Silent) {
Write-Host "Analyzing OU requirements..." -ForegroundColor Cyan
}
if ($Logging) {
Write-TierModelLog -LogPath $script:LogFilePath -Level 'Info' -Message "Starting OU deployment - Mode: $(if ($Apply) { 'EXECUTION' } else { 'PLANNING' })"
}
# Generate OU plan
$plan = Get-TierModelOu -Config $Config -DomainController $DomainController -IncludeDetails
if ($Logging) {
Write-TierModelLog -LogPath $script:LogFilePath -Level 'Info' -Message "OU plan generated - Total: $($plan.Summary.TotalInConfig), ToCreate: $($plan.Summary.ToCreate), Existing: $($plan.Summary.ExistingCount)"
}
# Display plan summary (only if not Silent)
if (-not $Silent) {
Write-Host "OU Plan Summary:" -ForegroundColor White
Write-Host " Total in Config: $($plan.Summary.TotalInConfig)" -ForegroundColor Gray
Write-Host " To Create: $($plan.Summary.ToCreate)" -ForegroundColor Yellow
Write-Host " Already Exist: $($plan.Summary.ExistingCount)" -ForegroundColor Green
if ($plan.Warnings.Count -gt 0) {
Write-Host "Warnings:" -ForegroundColor Yellow
$plan.Warnings | ForEach-Object { Write-Host " - $_" -ForegroundColor Yellow }
}
if ($plan.PSObject.Properties.Name -contains 'Errors' -and $plan.Errors -and @($plan.Errors).Count -gt 0) {
Write-Host "Errors:" -ForegroundColor Red
$plan.Errors | ForEach-Object { Write-Host " - $($_.Message)" -ForegroundColor Red }
return $plan
}
# Show planned actions
if ($plan.PSObject.Properties.Name -contains 'Actions' -and $plan.Actions -and @($plan.Actions).Count -gt 0) {
Write-Host "" # Blank line for spacing
Write-Host "Planned Actions:" -ForegroundColor Cyan
$plan.Actions | ForEach-Object {
Write-Host " ■ Create OU: $($_.Name)" -ForegroundColor Yellow
}
} else {
Write-Host " No actions needed - all OUs exist." -ForegroundColor Green
}
}
# Return early if errors (regardless of Silent mode)
if ($plan.PSObject.Properties.Name -contains 'Errors' -and $plan.Errors -and @($plan.Errors).Count -gt 0) {
# Create a consistent result object when there are plan errors
$errorResult = [PSCustomObject]@{
EntityType = 'OU'
Applied = @()
Skipped = @()
Errors = $plan.Errors
DurationMs = 0
Converged = $false
PlanErrors = $true
}
return $errorResult
}
# Apply changes if requested
if ($Apply) {
if ($plan.PSObject.Properties.Name -contains 'Actions' -and $plan.Actions -and @($plan.Actions).Count -gt 0) {
# Execute the deployment
if (-not $Silent) {
Write-Host "Applying OU changes..." -ForegroundColor Cyan
}
if ($Logging) {
Write-TierModelLog -LogPath $script:LogFilePath -Level 'Info' -Message "Applying OU changes - $($plan.Actions.Count) actions to execute"
}
try {
$result = New-TierModelOu -Plan $plan -DomainController $DomainController
# Validate that we got the expected result structure
if (-not $result) {
throw "New-TierModelOu returned null"
}
if (-not ($result.PSObject.Properties.Name -contains 'Applied')) {
throw "New-TierModelOu returned object without Applied property. Properties: $($result.PSObject.Properties.Name -join ', ')"
}
# Add entity type to result for consolidated reporting
$result | Add-Member -NotePropertyName 'EntityType' -NotePropertyValue 'OU' -Force
}
catch {
# Create fallback result if New-TierModelOu fails
Write-Host "ERROR: OU deployment failed: $($_.Exception.Message)" -ForegroundColor Red
$result = [PSCustomObject]@{
EntityType = 'OU'
Applied = @()
Skipped = @()
Errors = @(@{
Message = "OU deployment failed: $($_.Exception.Message)"
Timestamp = Get-Date
})
DurationMs = 0
Converged = $false
}
}
# Store result details for consolidated results section (removed individual Application Results for cleaner output)
if ($Logging) {
Write-TierModelLog -LogPath $script:LogFilePath -Level 'Info' -Message "OU deployment completed - Applied: $($result.Applied.Count), Skipped: $($result.Skipped.Count), Errors: $($result.Errors.Count), Duration: $($result.DurationMs)ms"
}
return $result
} else {
# No actions needed - create execution result object
$result = [PSCustomObject]@{
EntityType = 'OU'
Applied = @()
Skipped = @()
Errors = @()
DurationMs = 0
Converged = $true
}
# No need to display message here since it was already shown in the planning phase
return $result
}
} # Planning mode - return plan structure with execution properties for consistency
if ($Logging) {
Write-TierModelLog -LogPath $script:LogFilePath -Level 'Info' -Message "OU planning completed - $($plan.Actions.Count) actions identified"
}
$planningResult = [PSCustomObject]@{
EntityType = 'OU'
Actions = $plan.Actions
Summary = $plan.Summary
Warnings = $plan.Warnings
Errors = $plan.Errors
Applied = @() # Empty for planning mode
Skipped = @() # Empty for planning mode
DurationMs = 0
Converged = (-not ($plan.PSObject.Properties.Name -contains 'Errors' -and $plan.Errors -and @($plan.Errors).Count -gt 0)) -and (-not ($plan.PSObject.Properties.Name -contains 'Actions' -and $plan.Actions -and @($plan.Actions).Count -gt 0))
PlanMode = $true
}
return $planningResult
}
function Invoke-GroupDeployment {
param(
[Parameter(Mandatory)] [object]$Config,
[Parameter(Mandatory)] [string]$DomainController,
[switch]$Apply,
[switch]$Silent # For FullDeployment - suppress progress output, return data only
)
if (-not $Silent) {
Write-Host "Analyzing Group requirements..." -ForegroundColor Cyan
}
# Generate deployment plan
$plan = Get-TierModelGroup -Config $Config -DomainController $DomainController -IncludeDetails
if (-not $Silent) {
Write-Host "Group Plan Summary:" -ForegroundColor White
Write-Host " Total in Config: $($plan.Summary.TotalInConfig)" -ForegroundColor Gray
Write-Host " To Create: $($plan.Summary.ToCreate)" -ForegroundColor Yellow
Write-Host " Already Exist: $($plan.Summary.ExistingCount)" -ForegroundColor Green
if ($plan.PSObject.Properties.Name -contains 'Warnings' -and $plan.Warnings -and @($plan.Warnings).Count -gt 0) {
Write-Host "Warnings:" -ForegroundColor Yellow
$plan.Warnings | ForEach-Object { Write-Host " - $_" -ForegroundColor Yellow }
}
if ($plan.PSObject.Properties.Name -contains 'Errors' -and $plan.Errors -and @($plan.Errors).Count -gt 0) {
Write-Host "Dependency Errors:" -ForegroundColor Red
# Deduplicate error messages for cleaner output by grouping by Message property
$uniqueErrors = $plan.Errors | Group-Object -Property Message | ForEach-Object { $_.Group[0] }
$uniqueErrors | Sort-Object Message | ForEach-Object { Write-Host " ❌ $($_.Message)" -ForegroundColor Red }
return $plan
}
# Show planned actions
if ($plan.PSObject.Properties.Name -contains 'Actions' -and $plan.Actions -and @($plan.Actions).Count -gt 0) {
Write-Host "" # Blank line for spacing
Write-Host "Planned Actions:" -ForegroundColor Cyan
$plan.Actions | ForEach-Object {
Write-Host " ■ Create Group: $($_.Name) ($($_.Data.samaccountname))" -ForegroundColor Yellow
}
} else {
Write-Host " No actions needed - all Groups exist." -ForegroundColor Green
}
}
# Return early if errors (regardless of Silent mode)
if ($plan.PSObject.Properties.Name -contains 'Errors' -and $plan.Errors -and @($plan.Errors).Count -gt 0) {
# Create a consistent result object when there are plan errors
$errorResult = [PSCustomObject]@{
EntityType = 'Group'
Actions = $plan.Actions
Applied = @()
Skipped = @()
Errors = $plan.Errors
DurationMs = 0
Converged = $false
PlanMode = $true
}
return $errorResult
}
# Apply changes if requested
if ($Apply) {
if ($plan.PSObject.Properties.Name -contains 'Actions' -and $plan.Actions -and @($plan.Actions).Count -gt 0) {
# Execute the deployment
if (-not $Silent) {
Write-Host "Applying Group changes..." -ForegroundColor Cyan
}
if ($Logging) {
Write-TierModelLog -LogPath $script:LogFilePath -Level 'Info' -Message "Applying Group changes - $($plan.Actions.Count) actions to execute"
}
try {
$result = New-TierModelGroup -Plan $plan -DomainController $DomainController
# Validate that we got the expected result structure
if (-not $result) {
throw "New-TierModelGroup returned null"
}
if (-not ($result.PSObject.Properties.Name -contains 'Applied')) {
throw "New-TierModelGroup returned object without Applied property. Properties: $($result.PSObject.Properties.Name -join ', ')"
}
# Add entity type to result for consolidated reporting
$result | Add-Member -NotePropertyName 'EntityType' -NotePropertyValue 'Group' -Force
}
catch {
# Create fallback result if New-TierModelGroup fails
Write-Host "ERROR: Group deployment failed: $($_.Exception.Message)" -ForegroundColor Red
$result = [PSCustomObject]@{
EntityType = 'Group'
Applied = @()
Skipped = @()
Errors = @(@{
Message = "Group deployment failed: $($_.Exception.Message)"
Timestamp = Get-Date
})
DurationMs = 0
Converged = $false
}
}
# Store result details for consolidated results section (removed individual Application Results for cleaner output)
if ($Logging) {
Write-TierModelLog -LogPath $script:LogFilePath -Level 'Info' -Message "Group deployment completed - Applied: $($result.Applied.Count), Skipped: $($result.Skipped.Count), Errors: $($result.Errors.Count), Duration: $($result.DurationMs)ms"
}
return $result
} else {
# No actions needed - create execution result object
$result = [PSCustomObject]@{
EntityType = 'Group'
Applied = @()
Skipped = @()
Errors = @()
DurationMs = 0
Converged = $true
}
# No need to display message here since it was already shown in the planning phase
return $result
}
} # Planning mode - return plan structure with execution properties for consistency
if ($Logging) {
Write-TierModelLog -LogPath $script:LogFilePath -Level 'Info' -Message "Group planning completed - $($plan.Actions.Count) actions identified"
}
$planningResult = [PSCustomObject]@{
EntityType = 'Group'
Actions = $plan.Actions
Summary = $plan.Summary
Warnings = $plan.Warnings
Errors = $plan.Errors
Applied = @() # Empty for planning mode
Skipped = @() # Empty for planning mode
DurationMs = 0
Converged = (-not ($plan.PSObject.Properties.Name -contains 'Errors' -and $plan.Errors -and @($plan.Errors).Count -gt 0)) -and (-not ($plan.PSObject.Properties.Name -contains 'Actions' -and $plan.Actions -and @($plan.Actions).Count -gt 0))
PlanMode = $true
}
return $planningResult
}
function Invoke-UserDeployment {
param(
[Parameter(Mandatory)] [object]$Config,
[Parameter(Mandatory)] [string]$DomainController,
[switch]$Apply, # When true, execute changes; when false, plan only
[switch]$Silent # For FullDeployment - suppress progress output, return data only
)
if (-not $Silent) {
Write-Host "Analyzing User requirements..." -ForegroundColor Cyan
}
# Generate deployment plan. Always suppress Get-TierModelUser's per-user "User exists"
# output so the -UserOnly console matches -GroupOnly (Get-TierModelGroup has no per-entity
# existence spam); the "User Plan Summary" below reports the counts instead.
$plan = Get-TierModelUser -Config $Config -DomainController $DomainController -Silent
# Show deployment plan summary (only if not Silent)
if (-not $Silent) {
Write-Host "User Plan Summary:" -ForegroundColor White
Write-Host " Total in Config: $($plan.Summary.TotalInConfig)" -ForegroundColor Gray
Write-Host " To Create: $($plan.Summary.ToCreate)" -ForegroundColor Yellow
Write-Host " To Update: $($plan.Summary.ToUpdate)" -ForegroundColor Yellow
Write-Host " Already Exist: $($plan.Summary.ExistingCount)" -ForegroundColor Green
# Handle optional Warnings property (may not exist in Get-TierModelUser)
if ($plan.PSObject.Properties.Name -contains 'Warnings' -and $plan.Warnings -and $plan.Warnings.Count -gt 0) {
Write-Host "Warnings:" -ForegroundColor Yellow
$plan.Warnings | ForEach-Object { Write-Host " - $_" -ForegroundColor Yellow }
}
# Handle optional Errors property (may not exist in Get-TierModelUser)
if ($plan.PSObject.Properties.Name -contains 'Errors' -and $plan.Errors -and $plan.Errors.Count -gt 0) {
Write-Host "Dependency Errors:" -ForegroundColor Red
# Deduplicate error messages for cleaner output by grouping by Message property
$uniqueErrors = $plan.Errors | Group-Object -Property Message | ForEach-Object { $_.Group[0] }
$uniqueErrors | Sort-Object Message | ForEach-Object { Write-Host " ❌ $($_.Message)" -ForegroundColor Red }
return $plan
}
# Show planned actions
if ($plan.Actions.Count -gt 0) {
Write-Host "" # Blank line for spacing
Write-Host "Planned Actions:" -ForegroundColor Cyan
$plan.Actions | ForEach-Object {
$actionName = if ($_.PSObject.Properties.Name -contains 'Name' -and $_.Name) { $_.Name } else { "Unknown" }
switch ($_.Action) {
'CreateUser' { Write-Host " ■ Create User: $actionName" -ForegroundColor Yellow }
'UpdateUserMembership' { Write-Host " ■ Add to Group: $actionName" -ForegroundColor Yellow }
default { Write-Host " ■ $($_.Action): $actionName" -ForegroundColor Yellow }
}
}
} else {
Write-Host " No actions needed - all Users exist." -ForegroundColor Green
}
}
# Return early if errors (regardless of Silent mode)
if ($plan.PSObject.Properties.Name -contains 'Errors' -and $plan.Errors -and $plan.Errors.Count -gt 0) {
# Create a consistent result object when there are plan errors
$errorResult = [PSCustomObject]@{
EntityType = 'User'
Actions = $plan.Actions
Applied = @()
Skipped = @()
Errors = $plan.Errors
DurationMs = 0
Converged = $false
PlanMode = $true
}
return $errorResult
}
# Execute deployment plan if Apply is specified
if ($Apply -and $plan.PSObject.Properties.Name -contains 'Actions' -and $plan.Actions -and @($plan.Actions).Count -gt 0) {
if (-not $Silent) {
Write-Host "Applying User deployment changes..." -ForegroundColor Cyan
}
# Explicitly pass parameters to avoid WhatIf parameter conflicts
$newUserParams = @{
Plan = $plan
DomainController = $DomainController
}
$executionResult = New-TierModelUser @newUserParams
# Convert execution result to match expected structure
$result = [PSCustomObject]@{
EntityType = 'User'
Applied = @(if ($executionResult.Executed -gt 0) { 1..$executionResult.Executed | ForEach-Object { [PSCustomObject]@{ Action = 'CreateUser'; Status = 'Success' } } })
Skipped = @(if ($executionResult.Skipped -gt 0) { 1..$executionResult.Skipped | ForEach-Object { [PSCustomObject]@{ Action = 'CreateUser'; Status = 'Skipped' } } })
Errors = $executionResult.Errors
DurationMs = $executionResult.DurationMs
Converged = $executionResult.Converged
}
# Store result details for consolidated results section (removed individual Application Results for cleaner output)
return $result
} else {
# No actions needed or planning mode - create execution result object
$hasErrors = $plan.PSObject.Properties.Name -contains 'Errors' -and $plan.Errors -and $plan.Errors.Count -gt 0
$result = [PSCustomObject]@{
EntityType = 'User'
Actions = $plan.Actions
Applied = @()
Skipped = @()
Errors = if ($hasErrors) { $plan.Errors } else { @() }
DurationMs = 0
Converged = -not $hasErrors
PlanMode = $true
}
# No need to display message here since it was already shown in the planning phase
return $result
}
}
function Invoke-OuAclDeployment {
param(
[Parameter(Mandatory)] [object]$Config,
[Parameter(Mandatory)] [string]$DomainController,
[switch]$Apply, # When true, execute changes; when false, plan only
[switch]$Silent # For FullDeployment - suppress progress output, return data only
)
if (-not $Silent) {
Write-Host "Analyzing OU ACL requirements..." -ForegroundColor Cyan
}
# Ensure GUID resolution functions are loaded (required by ACL processing)
if (-not (Get-Command Resolve-TierModelGuid -ErrorAction SilentlyContinue)) {
. "$PSScriptRoot\modules\TierModel\public\Resolve-TierModelGuid.ps1"
}
if (-not (Get-Command Resolve-DomainSpecificGuid -ErrorAction SilentlyContinue)) {
. "$PSScriptRoot\modules\TierModel\public\Resolve-DomainSpecificGuid.ps1"
}
# Generate deployment plan
$plan = Get-TierModelOuAcl -Config $Config -DomainController $DomainController
# Show deployment plan summary (only if not Silent)
if (-not $Silent) {
# Debug: Check plan structure
if (-not $plan) {
Write-Host "ERROR: Plan is null" -ForegroundColor Red
return [PSCustomObject]@{ EntityType = 'OuAcl'; Applied = @(); Skipped = @(); Errors = @("Plan is null"); DurationMs = 0; Converged = $false }
}
if (-not $plan.PSObject.Properties.Name -contains 'Summary' -or -not $plan.Summary) {
Write-Host "ERROR: Plan Summary is missing" -ForegroundColor Red
return [PSCustomObject]@{ EntityType = 'OuAcl'; Applied = @(); Skipped = @(); Errors = @("Plan Summary is missing"); DurationMs = 0; Converged = $false }
}
Write-Host "OU ACL Plan Summary:" -ForegroundColor White
Write-Host " Total in Config: $($plan.Summary.TotalActions)" -ForegroundColor Gray
Write-Host " To Create: $($plan.Summary.CreateActions)" -ForegroundColor Yellow
Write-Host " Already Exist: $(($plan.Summary.TotalActions) - ($plan.Summary.CreateActions))" -ForegroundColor Green
# Handle optional Errors property and show dependency errors
if ($plan.PSObject.Properties.Name -contains 'Errors' -and $plan.Errors -and $plan.Errors.Count -gt 0) {
Write-Host "Dependency Errors:" -ForegroundColor Red
# Deduplicate error messages for cleaner output by grouping by Message property
$uniqueErrors = $plan.Errors | Group-Object -Property Message | ForEach-Object { $_.Group[0] }
$uniqueErrors | Sort-Object Message | ForEach-Object { Write-Host " ❌ $($_.Message)" -ForegroundColor Red }
}
# Show planned actions
if ($plan.Actions -and @($plan.Actions).Count -gt 0) {
Write-Host "" # Blank line for spacing
Write-Host "Planned Actions ($($plan.Actions.Count) ACEs):" -ForegroundColor Cyan
# Group by identity reference to show all ACEs for each principal
$groupedActions = $plan.Actions | Group-Object -Property {
if ($_.Data -and $_.Data.identityreference) {
$_.Data.identityreference
} else {
'Unknown'
}
}
foreach ($group in $groupedActions) {
Write-Host " Principal: $($group.Name) ($($group.Count) ACE(s))" -ForegroundColor Yellow
foreach ($action in $group.Group) {
if ($action.Data) {
$rights = if ($action.Data.activedirectoryrights) { $action.Data.activedirectoryrights -join ', ' } else { 'Unknown' }
$objectType = if ($action.Data.objecttype) { $action.Data.objecttype } else { 'All Objects' }
$inheritance = if ($action.Data.activeDirectorysecurityinheritance) { $action.Data.activeDirectorysecurityinheritance } else { 'Unknown' }
Write-Host " ■ Rights: [$rights] | ObjectType: $objectType | Inheritance: $inheritance" -ForegroundColor White
} else {
Write-Host " ■ Create ACL (details unavailable)" -ForegroundColor White
}
}
}
} elseif ($plan.PSObject.Properties.Name -contains 'Errors' -and $plan.Errors -and $plan.Errors.Count -eq 0) {
Write-Host " No actions needed - all OU ACL delegations exist." -ForegroundColor Green
}
}
# Execute deployment plan if Apply is specified
if ($Apply -and $plan.PSObject.Properties.Name -contains 'Actions' -and $plan.Actions -and @($plan.Actions).Count -gt 0) {
if (-not $Silent) {
Write-Host "Applying OU ACL deployment changes..." -ForegroundColor Cyan
}
# Explicitly pass parameters to avoid WhatIf parameter conflicts
$newOuAclParams = @{
Plan = $plan
DomainController = $DomainController
Config = $config
}
$executionResult = New-TierModelOuAcl @newOuAclParams
# Convert execution result to match expected structure
$result = [PSCustomObject]@{
EntityType = 'OuAcl'
Applied = @(if ($executionResult.Executed -gt 0) { 1..$executionResult.Executed | ForEach-Object { [PSCustomObject]@{ Action = 'CreateAcl'; Status = 'Success' } } })
Skipped = @(if ($executionResult.Skipped -gt 0) { 1..$executionResult.Skipped | ForEach-Object { [PSCustomObject]@{ Action = 'CreateAcl'; Status = 'Skipped' } } })
Errors = $executionResult.Errors
DurationMs = $executionResult.DurationMs
Converged = $executionResult.Converged
}
# Application Results are now shown in the consolidated section - removed duplicate display
return $result
} else {
# No actions needed or planning mode - create execution result object
$hasErrors = $plan.PSObject.Properties.Name -contains 'Errors' -and $plan.Errors -and @($plan.Errors).Count -gt 0
$result = [PSCustomObject]@{
EntityType = 'OuAcl'
Actions = $plan.Actions # Include Actions for planning mode count display
Applied = @()
Skipped = @()
Errors = if ($hasErrors) { $plan.Errors } else { @() }
DurationMs = 0
Converged = -not $hasErrors
}
if (-not $Silent -and $plan.PSObject.Properties.Name -contains 'Actions' -and $plan.Actions -and @($plan.Actions).Count -eq 0 -and -not $hasErrors) {
Write-Host "No OU ACL changes needed - all ACL delegations already exist." -ForegroundColor Green
}
return $result
}
}
function Invoke-GpoDeployment {
param(
[Parameter(Mandatory)] [object]$Config,
[Parameter(Mandatory)] [string]$DomainController,
[switch]$Apply, # When true, execute changes; when false, plan only
[switch]$Silent # For FullDeployment - suppress progress output, return data only
)
if (-not $Silent) {
Write-Host "$(if ($Apply) { 'Executing' } else { 'Planning' }) GPO deployment..." -ForegroundColor Cyan
}
# First, check for dependency errors with silent mode
$planCheck = Get-TierModelGpo -Config $Config -DomainController $DomainController -Silent
# If there are dependency errors, generate plan again with silent mode and return early
if ($planCheck.PSObject.Properties.Name -contains 'Errors' -and $planCheck.Errors -and $planCheck.Errors.Count -gt 0) {
$plan = $planCheck # Use the silent plan
if (-not $Silent) {
Write-Host "Dependency Errors:" -ForegroundColor Red
# Deduplicate error messages for cleaner output by grouping by Message property
$uniqueErrors = $plan.Errors | Group-Object -Property Message | ForEach-Object { $_.Group[0] }
$uniqueErrors | Sort-Object Message | ForEach-Object { Write-Host " ❌ $($_.Message)" -ForegroundColor Red }
}
return $plan
}
# No dependency errors, use the silent plan and show the visual output manually (unless Silent mode)
$plan = $planCheck # Use the existing silent plan for all cases
if (-not $Silent) {
# Show GPO Plan Summary before the individual actions (like Users deployment)
Write-Host "GPO Plan Summary:" -ForegroundColor White
Write-Host " Total in Config: $($plan.Summary.TotalInConfig)" -ForegroundColor Gray
Write-Host " To Create: $($plan.Summary.CreateActions)" -ForegroundColor Yellow
Write-Host " To Import: $($plan.Summary.ImportActions)" -ForegroundColor Yellow
Write-Host " To Configure: $($plan.Summary.ConfigureActions)" -ForegroundColor Yellow
Write-Host " To Link: $($plan.Summary.LinkActions)" -ForegroundColor Yellow
Write-Host " Already Exist: $($plan.Summary.ExistingCount)" -ForegroundColor Green
Write-Host "" # Blank line before actions
# Generate the visual GPO analysis output (the format you want to keep)
$null = Get-TierModelGpo -Config $Config -DomainController $DomainController
# Show warnings if present
if ($plan.PSObject.Properties.Name -contains 'Warnings' -and $plan.Warnings -and $plan.Warnings.Count -gt 0) {
Write-Host "" # Blank line for spacing
Write-Host "Warnings:" -ForegroundColor Yellow
$plan.Warnings | ForEach-Object { Write-Host " - $_" -ForegroundColor Yellow }
}
}
# Return early if errors (regardless of Silent mode)
if ($plan.PSObject.Properties.Name -contains 'Errors' -and $plan.Errors -and $plan.Errors.Count -gt 0) {
# Create a consistent result object when there are plan errors
$errorResult = [PSCustomObject]@{
EntityType = 'GPO'
Actions = $plan.Actions
Applied = @()
Skipped = @()
Errors = $plan.Errors
DurationMs = 0
Converged = $false
PlanMode = $true
}
return $errorResult
}
# Execute deployment plan if Apply is specified
if ($Apply -and $plan -and $plan.Actions -and $plan.Actions.Count -gt 0) {
if (-not $Silent) {
Write-Host "Applying GPO deployment changes..." -ForegroundColor Cyan
}
$totalExecuted = 0
$totalFailed = 0
$totalSkipped = 0
$allErrors = @()
$overallConverged = $true
$totalDuration = 0
# Phase 1: Create GPOs
$createActions = @($plan.Actions | Where-Object { $_.Action -eq 'CreateGPO' })
if ($createActions.Count -gt 0) {
if (-not $Silent) { Write-Host " Phase 1: Creating GPOs..." -ForegroundColor Cyan }
$createPlan = [PSCustomObject]@{ Actions = $createActions; Config = $Config }
$createResult = New-TierModelGpo -Plan $createPlan -DomainController $DomainController
$totalExecuted += $createResult.Executed
$totalFailed += $createResult.Failed
$totalSkipped += $createResult.Skipped
$allErrors += $createResult.Errors
$totalDuration += $createResult.DurationMs
if (-not $createResult.Converged) { $overallConverged = $false }
# Stop if all GPOs failed in this phase
if ($createResult.Failed -gt 0 -and $createResult.Executed -eq 0) {
if (-not $Silent) { Write-Host " Phase 1 failed completely - stopping GPO deployment" -ForegroundColor Red }
return [PSCustomObject]@{
Executed = $totalExecuted; Failed = $totalFailed; Skipped = $totalSkipped
Errors = $allErrors; Converged = $false; DurationMs = $totalDuration
}
}
}
# Phase 2: Import GPO settings
$importActions = @($plan.Actions | Where-Object { $_.Action -eq 'ImportGPO' })
if ($importActions.Count -gt 0) {
if (-not $Silent) { Write-Host " Phase 2: Importing GPO settings..." -ForegroundColor Cyan }
$importPlan = [PSCustomObject]@{ Actions = $importActions; Config = $Config }
try {
$importResult = Import-TierModelGpo -Plan $importPlan -DomainController $DomainController
if ($importResult) {
$totalExecuted += $importResult.Executed
$totalFailed += $importResult.Failed
$totalSkipped += $importResult.Skipped
$allErrors += $importResult.Errors
$totalDuration += $importResult.DurationMs
if (-not $importResult.Converged) { $overallConverged = $false }
} else {
Write-Host " WARNING: Import result is null" -ForegroundColor Yellow
$totalFailed += $importActions.Count
}
} catch {
Write-Host " ERROR: Import-TierModelGpo failed - $($_.Exception.Message)" -ForegroundColor Red
$allErrors += $_.Exception.Message
$totalFailed += $importActions.Count
$overallConverged = $false