-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAdd-ComputerToADGroup.ps1
More file actions
777 lines (650 loc) · 27.9 KB
/
Copy pathAdd-ComputerToADGroup.ps1
File metadata and controls
777 lines (650 loc) · 27.9 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
#Requires -Version 5.1
<#
.SYNOPSIS
Adds the current computer account to one or more Active Directory groups during a ConfigMgr Task Sequence.
.DESCRIPTION
Reads ADGroupUserName and ADGroupPassword from explicit custom Task Sequence variables.
The script runs as Local System in the full Windows phase of a ConfigMgr Task Sequence after domain join and a restart, connects to Active Directory by using Kerberos over LDAPS on TCP 636, adds the local computer account to the requested group or groups when needed, and verifies direct membership before returning success.
Domain controllers in the computer's own Active Directory site are tried first; all discovered controllers remain available for failover.
The script intentionally avoids Network Access Account retrieval, hidden reserved Task Sequence credential variables, legacy command-based credential helpers, LDAP fallback, explicit NTLM LDAP mode, and command-line passwords.
Credential variables should be created immediately before the script step and cleared immediately afterward with native Task Sequence steps.
.PARAMETER GroupName
One or more Active Directory group sAMAccountName values.
.PARAMETER RetryCount
Total passes, including the first attempt, for transient readiness or directory issues. Default: 3.
.PARAMETER RetryDelaySeconds
Delay between retry passes. Default: 300 seconds.
.PARAMETER TimeoutSeconds
Timeout for each LDAP connection or operation, not for the entire run. Default: 30 seconds.
.PARAMETER AuthenticationMode
Kerberos by default. Negotiate requires AllowNtlmV2 and an explicit NTLMv2-only client policy.
.PARAMETER DirectoryTransport
LDAPS on TCP 636 by default. SignedLdap explicitly selects TCP 389 with signing and sealing.
.PARAMETER AllowNtlmV2
Permits Negotiate when LmCompatibilityLevel is explicitly set to 3, 4, or 5.
The script does not change policy or determine which protocol Negotiate selected.
.EXAMPLE
.\Add-ComputerToADGroup.ps1 -GroupName "Workstation-Certificate-AutoEnroll"
Adds the local computer account to one group and verifies direct membership.
.EXAMPLE
.\Add-ComputerToADGroup.ps1 -GroupName "Group-A","Group-B"
Adds the local computer account to multiple groups and returns success only if all requested operations succeed.
.LINK
https://github.com/vartaxe/ConfigMgr-OSD-AddComputerToADGroup
.NOTES
FileName: Add-ComputerToADGroup.ps1
Author: Claudio Mendes (vartaxe)
Contact: vartaxe@outlook.com | https://github.com/vartaxe
Version: 1.0.0
Target: Windows PowerShell 5.1 during a ConfigMgr Task Sequence in full Windows.
LogFile: AddComputerToADGroup.log
#>
[CmdletBinding()]
[Diagnostics.CodeAnalysis.SuppressMessageAttribute(
'PSAvoidUsingConvertToSecureStringWithPlainText',
'',
Justification = 'The password is supplied at runtime through a hidden ConfigMgr Task Sequence variable, converted immediately to PSCredential, never logged, and not stored in the script.'
)]
param(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[string[]]$GroupName,
[Parameter(Mandatory = $false)]
[ValidateRange(1, 10)]
[int]$RetryCount = 3,
[Parameter(Mandatory = $false)]
[ValidateRange(0, 3600)]
[int]$RetryDelaySeconds = 300,
[Parameter(Mandatory = $false)]
[ValidateRange(5, 300)]
[int]$TimeoutSeconds = 30,
[ValidateSet('Kerberos', 'Negotiate')]
[string]$AuthenticationMode = 'Kerberos',
[ValidateSet('LDAPS', 'SignedLdap')]
[string]$DirectoryTransport = 'LDAPS',
[switch]$AllowNtlmV2
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
$script:Version = '1.0.0'
$script:TaskSequenceEnvironment = $null
$script:LogPath = $null
$script:Component = 'AddComputerToADGroup'
function Get-TaskSequenceEnvironment {
try {
return New-Object -ComObject Microsoft.SMS.TSEnvironment -ErrorAction Stop
}
catch {
throw 'Microsoft.SMS.TSEnvironment is unavailable. Run this script inside an active ConfigMgr Task Sequence.'
}
}
function Get-TaskSequenceVariable {
param(
[Parameter(Mandatory = $true)]
$Environment,
[Parameter(Mandatory = $true)]
[string]$Name
)
$Value = [string]$Environment.Value($Name)
if ([string]::IsNullOrWhiteSpace($Value)) {
throw "Task Sequence variable '$Name' is empty."
}
return $Value
}
function Initialize-Log {
$Folder = Join-Path -Path $env:WINDIR -ChildPath 'Temp'
try {
$TaskSequenceLogPath = [string]$script:TaskSequenceEnvironment.Value('_SMSTSLogPath')
if (-not [string]::IsNullOrWhiteSpace($TaskSequenceLogPath)) {
if (Test-Path -LiteralPath $TaskSequenceLogPath -PathType Container) {
$Folder = $TaskSequenceLogPath
}
}
}
catch {
Write-Warning 'Cannot read _SMSTSLogPath; using the Windows Temp log location.'
}
if (-not (Test-Path -LiteralPath $Folder -PathType Container)) {
[void](New-Item -Path $Folder -ItemType Directory -Force)
}
$script:LogPath = Join-Path -Path $Folder -ChildPath 'AddComputerToADGroup.log'
}
function Write-Log {
param(
[Parameter(Mandatory = $true)]
[string]$Message,
[ValidateSet('INFO', 'WARN', 'ERROR')]
[string]$Level = 'INFO'
)
$Safe = $Message -replace '[\r\n]+', ' ' -replace '\]LOG\]!>', ']LOG removed>'
try {
$Type = switch ($Level) {
'WARN' {
2
}
'ERROR' {
3
}
default {
1
}
}
$Now = [DateTimeOffset]::Now
$Bias = [int]$Now.Offset.TotalMinutes
$Time = $Now.ToString('HH:mm:ss.fff') + ('{0:+0;-0;+0}' -f $Bias)
$Line = '<![LOG[{0}]LOG]!><time="{1}" date="{2}" component="{3}" context="" type="{4}" thread="{5}" file="">' -f $Safe, $Time, $Now.ToString('MM-dd-yyyy'), $script:Component, $Type, [Threading.Thread]::CurrentThread.ManagedThreadId
Add-Content -LiteralPath $script:LogPath -Value $Line -Encoding UTF8 -ErrorAction Stop
}
catch {
Write-Warning 'Cannot write AddComputerToADGroup.log; check the log directory and permissions.'
}
if ($Level -ne 'INFO') {
Write-Warning "[$Level] $Safe"
}
}
function ConvertTo-LdapFilterValue {
param(
[Parameter(Mandatory = $true)]
[string]$Value
)
$Builder = New-Object System.Text.StringBuilder
foreach ($Character in $Value.ToCharArray()) {
switch ([int][char]$Character) {
0 { [void]$Builder.Append('\00') }
40 { [void]$Builder.Append('\28') }
41 { [void]$Builder.Append('\29') }
42 { [void]$Builder.Append('\2a') }
92 { [void]$Builder.Append('\5c') }
default { [void]$Builder.Append($Character) }
}
}
return $Builder.ToString()
}
function Get-PreferredDomainControllerOrder {
param(
[Parameter(Mandatory = $true)]
[AllowNull()]
[AllowEmptyCollection()]
$Controller,
[Parameter(Mandatory = $false)]
[AllowNull()]
[AllowEmptyString()]
[string]$SiteName
)
$LocalSite = New-Object System.Collections.Generic.List[string]
$OtherSite = New-Object System.Collections.Generic.List[string]
foreach ($Entry in @($Controller)) {
if ($null -eq $Entry) { continue }
$Name = $null
try { $Name = [string]$Entry.Name } catch { $Name = $null }
if ([string]::IsNullOrWhiteSpace($Name)) { continue }
$Name = $Name.Trim().ToLowerInvariant()
# A domain controller that cannot report its site is treated as remote, never skipped.
$EntrySite = $null
try { $EntrySite = [string]$Entry.SiteName } catch { $EntrySite = $null }
if ((-not [string]::IsNullOrWhiteSpace($SiteName)) -and ($EntrySite -eq $SiteName)) {
$LocalSite.Add($Name)
}
else {
$OtherSite.Add($Name)
}
}
return @(
@(@($LocalSite | Sort-Object) + @($OtherSite | Sort-Object)) | Select-Object -Unique
)
}
function Get-ComputerSiteName {
$Site = $null
try {
$Site = [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]::GetComputerSite()
return [string]$Site.Name
}
catch {
return $null
}
finally {
if ($null -ne $Site) {
$Site.Dispose()
}
}
}
function Get-DomainControllerName {
$Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain()
try {
$Controllers = @($Domain.DomainControllers)
try {
$SiteName = Get-ComputerSiteName
if ([string]::IsNullOrWhiteSpace($SiteName)) {
Write-Log -Level 'WARN' -Message 'The local Active Directory site could not be determined; using name-ordered domain controller discovery.'
}
else {
Write-Log -Message "Preferring domain controllers in the local site: $SiteName"
}
return Get-PreferredDomainControllerOrder -Controller $Controllers -SiteName $SiteName
}
finally {
foreach ($Controller in $Controllers) {
$Controller.Dispose()
}
}
}
finally {
$Domain.Dispose()
}
}
function Connect-LdapServer {
param(
[string]$Server,
[Management.Automation.PSCredential]$Credential,
[int]$Timeout,
[string]$Authentication,
[string]$Transport
)
$Port = if ($Transport -eq 'LDAPS') {
636
}
else {
389
}
$Identifier = New-Object DirectoryServices.Protocols.LdapDirectoryIdentifier -ArgumentList $Server, $Port, $true, $false
$Connection = New-Object DirectoryServices.Protocols.LdapConnection -ArgumentList $Identifier
try {
$Connection.AuthType = if ($Authentication -eq 'Kerberos') {
[DirectoryServices.Protocols.AuthType]::Kerberos
}
else {
[DirectoryServices.Protocols.AuthType]::Negotiate
}
$Connection.Credential = $Credential.GetNetworkCredential();
$Connection.SessionOptions.ProtocolVersion = 3;
$Connection.Timeout = New-TimeSpan -Seconds $Timeout
if ($Transport -eq 'LDAPS') {
$Connection.SessionOptions.SecureSocketLayer = $true
}
else {
$Connection.SessionOptions.Signing = $true;
$Connection.SessionOptions.Sealing = $true
}
$Connection.Bind();
return $Connection
}
catch {
$Connection.Dispose();
throw
}
}
function Assert-AuthenticationPolicy {
param([string]$Authentication, [string]$Transport, [bool]$AllowFallback)
if ($Authentication -eq 'Negotiate') {
if (-not $AllowFallback) {
throw 'Negotiate requires explicit -AllowNtlmV2 permission.'
}
$Policy = Get-ItemProperty -LiteralPath 'HKLM:\SYSTEM\CurrentControlSet\Control\Lsa' -ErrorAction Stop
$Level = $Policy.PSObject.Properties['LmCompatibilityLevel']
if ($null -eq $Level -or $Level.Value -isnot [int] -or $Level.Value -notin @(3, 4, 5)) {
throw 'Negotiate requires an explicit LmCompatibilityLevel of 3, 4, or 5; configure NTLMv2-only client policy before retrying.'
}
Write-Log -Level 'WARN' -Message 'Compatibility enabled: Negotiate with NTLMv2-only client policy. The negotiated protocol is not reported.'
}
if ($Transport -eq 'SignedLdap') {
Write-Log -Level 'WARN' -Message 'Compatibility enabled: SignedLdap on TCP 389 with signing and sealing required.'
}
}
function Get-LdapAttributeValue {
param(
[Parameter(Mandatory = $true)]
$Entry,
[Parameter(Mandatory = $true)]
[string]$Name
)
if ($Entry.Attributes.Contains($Name)) {
if ($Entry.Attributes[$Name].Count -gt 0) {
return [string]$Entry.Attributes[$Name].GetValues([string])[0]
}
}
return $null
}
function Get-DefaultNamingContext {
param(
[Parameter(Mandatory = $true)]
$Connection
)
$Request = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList '', '(objectClass=*)', ([System.DirectoryServices.Protocols.SearchScope]::Base), @('defaultNamingContext')
$Response = $Connection.SendRequest($Request)
if ($Response.Entries.Count -ne 1) {
throw 'RootDSE lookup failed.'
}
$NamingContext = Get-LdapAttributeValue -Entry $Response.Entries[0] -Name 'defaultNamingContext'
if ([string]::IsNullOrWhiteSpace($NamingContext)) {
throw 'RootDSE did not return defaultNamingContext.'
}
return $NamingContext
}
function Find-LdapObject {
param(
[Parameter(Mandatory = $true)]
$Connection,
[Parameter(Mandatory = $true)]
[string]$SearchBase,
[Parameter(Mandatory = $true)]
[string]$Filter,
[Parameter(Mandatory = $true)]
[string]$Description
)
$Request = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $SearchBase, $Filter, ([System.DirectoryServices.Protocols.SearchScope]::Subtree), @('distinguishedName')
$Response = $Connection.SendRequest($Request)
if ($Response.Entries.Count -eq 0) {
throw "$Description was not found."
}
if ($Response.Entries.Count -gt 1) {
throw "$Description returned multiple results."
}
return $Response.Entries[0]
}
function Test-DirectMembership {
param(
[Parameter(Mandatory = $true)]
$Connection,
[Parameter(Mandatory = $true)]
[string]$GroupDistinguishedName,
[Parameter(Mandatory = $true)]
[string]$ComputerDistinguishedName
)
$EscapedComputer = ConvertTo-LdapFilterValue -Value $ComputerDistinguishedName
$Filter = '(&(objectClass=group)(member={0}))' -f $EscapedComputer
$Request = New-Object System.DirectoryServices.Protocols.SearchRequest -ArgumentList $GroupDistinguishedName, $Filter, ([System.DirectoryServices.Protocols.SearchScope]::Base), @('distinguishedName')
$Response = $Connection.SendRequest($Request)
return ($Response.Entries.Count -eq 1)
}
function Invoke-DirectMembershipAdd {
param(
[Parameter(Mandatory = $true)]
$Connection,
[Parameter(Mandatory = $true)]
[string]$GroupDistinguishedName,
[Parameter(Mandatory = $true)]
[string]$ComputerDistinguishedName
)
$Change = New-Object System.DirectoryServices.Protocols.DirectoryAttributeModification
$Change.Name = 'member'
$Change.Operation = [System.DirectoryServices.Protocols.DirectoryAttributeOperation]::Add
[void]$Change.Add($ComputerDistinguishedName)
$Request = New-Object System.DirectoryServices.Protocols.ModifyRequest -ArgumentList $GroupDistinguishedName, $Change
try {
[void]$Connection.SendRequest($Request)
}
catch {
$Exception = Get-DirectoryException -ErrorRecord $_
if ($Exception -isnot [System.DirectoryServices.Protocols.DirectoryOperationException] -or
$null -eq $Exception.Response -or
$Exception.Response.ResultCode -ne [System.DirectoryServices.Protocols.ResultCode]::AttributeOrValueExists) {
throw
}
}
}
function Get-DirectoryException {
param(
[Parameter(Mandatory = $true)]
[System.Management.Automation.ErrorRecord]$ErrorRecord
)
$Exception = $ErrorRecord.Exception
while ($null -ne $Exception.InnerException) {
# Preserve actionable directory codes before unwrapping an exception's diagnostic cause.
if ($Exception -is [System.DirectoryServices.Protocols.LdapException] -or
($Exception -is [System.DirectoryServices.Protocols.DirectoryOperationException] -and $null -ne $Exception.Response) -or
$Exception -is [System.UnauthorizedAccessException]) {
break
}
$Exception = $Exception.InnerException
}
return $Exception
}
function Get-SafeErrorMessage {
param(
[Parameter(Mandatory = $true)]
[System.Management.Automation.ErrorRecord]$ErrorRecord
)
$Exception = Get-DirectoryException -ErrorRecord $ErrorRecord
if ($Exception -is [System.DirectoryServices.Protocols.LdapException]) {
return "LDAP error code $($Exception.ErrorCode)."
}
if ($Exception -is [System.DirectoryServices.Protocols.DirectoryOperationException] -and $null -ne $Exception.Response) {
return "Directory result: $($Exception.Response.ResultCode)."
}
# Only locally defined, credential-free messages may pass through to either log.
$KnownMessages = @(
'Microsoft.SMS.TSEnvironment is unavailable. Run this script inside an active ConfigMgr Task Sequence.',
"Task Sequence variable 'ADGroupUserName' is empty.",
"Task Sequence variable 'ADGroupPassword' is empty.",
'Windows PE is not supported. Run this script after Windows setup, domain join, and a restart.',
'Negotiate requires explicit -AllowNtlmV2 permission.',
'Negotiate requires an explicit LmCompatibilityLevel of 3, 4, or 5; configure NTLMv2-only client policy before retrying.',
'No valid group names were provided.',
'The computer secure channel is not operational.',
'No domain controllers were discovered.',
'RootDSE lookup failed.',
'RootDSE did not return defaultNamingContext.',
'Membership verification failed.',
'One or more group operations failed.'
)
if ($Exception.Message -cin $KnownMessages) {
return $Exception.Message
}
if ($Exception.Message -match "^AD group '.*' was not found\.$") {
return 'Requested AD group was not found.'
}
if ($Exception.Message -match "^AD group '.*' returned multiple results\.$") {
return 'Requested AD group returned multiple results.'
}
if ($Exception.Message -match "^Computer account '.*' was not found\.$") {
return 'Computer account was not found.'
}
if ($Exception.Message -match "^Computer account '.*' returned multiple results\.$") {
return 'Computer account returned multiple results.'
}
return "Operation failed ($($Exception.GetType().Name)); raw exception details are omitted to protect credentials."
}
function Test-PermanentDirectoryError {
param(
[Parameter(Mandatory = $true)]
[System.Management.Automation.ErrorRecord]$ErrorRecord
)
$Exception = Get-DirectoryException -ErrorRecord $ErrorRecord
if ($Exception -is [System.DirectoryServices.Protocols.LdapException]) {
return ($Exception.ErrorCode -in @(8, 13, 19, 34, 49, 50, 53, 64, 65, 67))
}
if ($Exception -is [System.DirectoryServices.Protocols.DirectoryOperationException] -and $null -ne $Exception.Response) {
$PermanentCodes = @(
[System.DirectoryServices.Protocols.ResultCode]::StrongAuthRequired,
[System.DirectoryServices.Protocols.ResultCode]::ConfidentialityRequired,
[System.DirectoryServices.Protocols.ResultCode]::InvalidDNSyntax,
[System.DirectoryServices.Protocols.ResultCode]::InsufficientAccessRights,
[System.DirectoryServices.Protocols.ResultCode]::ConstraintViolation,
[System.DirectoryServices.Protocols.ResultCode]::ObjectClassViolation,
[System.DirectoryServices.Protocols.ResultCode]::NamingViolation,
[System.DirectoryServices.Protocols.ResultCode]::UnwillingToPerform
)
return ($Exception.Response.ResultCode -in $PermanentCodes)
}
if ($Exception.Message -match "^AD group '.*' was not found\.$") {
return $true
}
if ($Exception.Message -match "^AD group '.*' returned multiple results\.$") {
return $true
}
if ($Exception -is [System.UnauthorizedAccessException]) {
return $true
}
return $false
}
function Get-OperationResult {
param(
[Parameter(Mandatory = $true)]
[bool]$Success,
[Parameter(Mandatory = $true)]
[string]$Status,
[Parameter(Mandatory = $false)]
[string]$Message = ''
)
return [pscustomobject]@{
Success = $Success
Status = $Status
Message = $Message
}
}
$ExitCode = 1
$Credential = $null
$SecurePassword = $null
$Password = $null
$UserName = $null
try {
Add-Type -AssemblyName System.DirectoryServices.Protocols
Add-Type -AssemblyName System.DirectoryServices
if ($env:SystemDrive -eq 'X:') {
throw 'Windows PE is not supported. Run this script after Windows setup, domain join, and a restart.'
}
$script:TaskSequenceEnvironment = Get-TaskSequenceEnvironment
Initialize-Log
Write-Log -Message "Add-ComputerToADGroup started. Version=$script:Version"
Assert-AuthenticationPolicy -Authentication $AuthenticationMode -Transport $DirectoryTransport -AllowFallback $AllowNtlmV2.IsPresent
$UserName = Get-TaskSequenceVariable -Environment $script:TaskSequenceEnvironment -Name 'ADGroupUserName'
$Password = Get-TaskSequenceVariable -Environment $script:TaskSequenceEnvironment -Name 'ADGroupPassword'
try {
$SecurePassword = ConvertTo-SecureString -String $Password -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $UserName, $SecurePassword
}
finally {
$Password = $null
}
$SeenGroups = @{}
$RequestedGroups = @(
foreach ($Name in $GroupName) {
$Name = $Name.Trim()
if (-not [string]::IsNullOrWhiteSpace($Name) -and -not $SeenGroups.ContainsKey($Name)) {
$SeenGroups[$Name] = $true
$Name
}
}
)
if ($RequestedGroups.Count -eq 0) {
throw 'No valid group names were provided.'
}
$Results = @{}
for ($Pass = 1; $Pass -le $RetryCount; $Pass++) {
$PendingGroups = @($RequestedGroups | Where-Object { -not $Results.ContainsKey($_) })
if ($PendingGroups.Count -eq 0) {
break
}
Write-Log -Message "Pass $Pass of $RetryCount. Pending=$($PendingGroups -join ',')"
try {
if (-not (Test-ComputerSecureChannel -ErrorAction Stop)) {
throw 'The computer secure channel is not operational.'
}
$DomainControllers = @(Get-DomainControllerName)
Write-Log -Message "Discovered domain controllers: $($DomainControllers.Count)"
if ($DomainControllers.Count -eq 0) {
throw 'No domain controllers were discovered.'
}
foreach ($DomainController in $DomainControllers) {
if (@($PendingGroups | Where-Object { -not $Results.ContainsKey($_) }).Count -eq 0) {
break
}
$Connection = $null
try {
$Connection = Connect-LdapServer -Server $DomainController -Credential $Credential -Timeout $TimeoutSeconds -Authentication $AuthenticationMode -Transport $DirectoryTransport
$NamingContext = Get-DefaultNamingContext -Connection $Connection
$ComputerSam = ConvertTo-LdapFilterValue -Value ($env:COMPUTERNAME + '$')
$ComputerFilter = '(&(objectCategory=computer)(sAMAccountName={0}))' -f $ComputerSam
$Computer = Find-LdapObject -Connection $Connection -SearchBase $NamingContext -Filter $ComputerFilter -Description "Computer account '$env:COMPUTERNAME'"
$ComputerDn = Get-LdapAttributeValue -Entry $Computer -Name 'distinguishedName'
foreach ($CurrentGroup in @($PendingGroups | Where-Object { -not $Results.ContainsKey($_) })) {
try {
$GroupSam = ConvertTo-LdapFilterValue -Value $CurrentGroup
$GroupFilter = '(&(objectCategory=group)(sAMAccountName={0}))' -f $GroupSam
$GroupEntry = Find-LdapObject -Connection $Connection -SearchBase $NamingContext -Filter $GroupFilter -Description "AD group '$CurrentGroup'"
$GroupDn = Get-LdapAttributeValue -Entry $GroupEntry -Name 'distinguishedName'
if (Test-DirectMembership -Connection $Connection -GroupDistinguishedName $GroupDn -ComputerDistinguishedName $ComputerDn) {
$Results[$CurrentGroup] = Get-OperationResult -Success $true -Status 'AlreadyMember'
}
else {
Invoke-DirectMembershipAdd -Connection $Connection -GroupDistinguishedName $GroupDn -ComputerDistinguishedName $ComputerDn
if (-not (Test-DirectMembership -Connection $Connection -GroupDistinguishedName $GroupDn -ComputerDistinguishedName $ComputerDn)) {
throw 'Membership verification failed.'
}
$Results[$CurrentGroup] = Get-OperationResult -Success $true -Status 'AddedAndVerified'
}
}
catch {
if (Test-PermanentDirectoryError -ErrorRecord $_) {
$Results[$CurrentGroup] = Get-OperationResult -Success $false -Status 'FailedPermanent' -Message (Get-SafeErrorMessage -ErrorRecord $_)
}
else {
Write-Log -Level 'WARN' -Message "Transient group failure on ${DomainController}: Group=$CurrentGroup; Error=$(Get-SafeErrorMessage -ErrorRecord $_)"
}
}
}
}
catch {
if (Test-PermanentDirectoryError -ErrorRecord $_) {
foreach ($CurrentGroup in @($PendingGroups | Where-Object { -not $Results.ContainsKey($_) })) {
$Results[$CurrentGroup] = Get-OperationResult -Success $false -Status 'FailedPermanent' -Message (Get-SafeErrorMessage -ErrorRecord $_)
}
break
}
Write-Log -Level 'WARN' -Message "Transient DC failure on ${DomainController}: $(Get-SafeErrorMessage -ErrorRecord $_)"
}
finally {
if ($null -ne $Connection) {
$Connection.Dispose()
}
}
}
}
catch {
Write-Log -Level 'WARN' -Message "Transient readiness failure: $(Get-SafeErrorMessage -ErrorRecord $_)"
}
$RemainingGroups = @($RequestedGroups | Where-Object { -not $Results.ContainsKey($_) })
if (($RemainingGroups.Count -gt 0) -and ($Pass -lt $RetryCount) -and ($RetryDelaySeconds -gt 0)) {
Start-Sleep -Seconds $RetryDelaySeconds
}
}
foreach ($CurrentGroup in $RequestedGroups) {
if (-not $Results.ContainsKey($CurrentGroup)) {
$Results[$CurrentGroup] = Get-OperationResult -Success $false -Status 'FailedTransient' -Message 'Retries exhausted.'
}
if ($Results[$CurrentGroup].Success) {
$LogLevel = 'INFO'
}
else {
$LogLevel = 'ERROR'
}
Write-Log -Level $LogLevel -Message "Summary: Group=$CurrentGroup; Result=$($Results[$CurrentGroup].Status); Message=$($Results[$CurrentGroup].Message)"
}
$FailedGroups = @($RequestedGroups | Where-Object { -not $Results[$_].Success })
if ($FailedGroups.Count -gt 0) {
throw 'One or more group operations failed.'
}
$ExitCode = 0
}
catch {
Write-Log -Level 'ERROR' -Message (Get-SafeErrorMessage -ErrorRecord $_)
$ExitCode = 1
}
finally {
if ($null -ne $SecurePassword) {
$SecurePassword.Dispose()
}
$Credential = $null
$SecurePassword = $null
$Password = $null
$UserName = $null
Write-Log -Message "Script exit code: $ExitCode"
}
if ($ExitCode -eq 0) {
Write-Output 'AD group operation completed successfully.'
}
else {
Write-Output 'AD group operation failed. See AddComputerToADGroup.log.'
}
exit $ExitCode