-
Notifications
You must be signed in to change notification settings - Fork 141
/
MSFT_xADComputer.psm1
587 lines (503 loc) · 21.6 KB
/
MSFT_xADComputer.psm1
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
$moduleRoot = Split-Path -Path $MyInvocation.MyCommand.Path -Parent
#region LocalizedData
$culture = 'en-us'
if (Test-Path -Path (Join-Path -Path $moduleRoot -ChildPath $PSUICulture))
{
$culture = $PSUICulture
}
$importLocalizedDataParams = @{
BindingVariable = 'LocalizedData'
Filename = 'MSFT_xADComputer.psd1'
BaseDirectory = $moduleRoot
UICulture = $culture
}
Import-LocalizedData @importLocalizedDataParams
#endregion
## Create a property map that maps the DSC resource parameters to the
## Active Directory computer attributes.
$adPropertyMap = @(
@{ Parameter = 'ComputerName'; ADProperty = 'cn'; }
@{ Parameter = 'Location'; }
@{ Parameter = 'DnsHostName'; }
@{ Parameter = 'ServicePrincipalNames'; }
@{ Parameter = 'UserPrincipalName'; }
@{ Parameter = 'DisplayName'; }
@{ Parameter = 'Path'; ADProperty = 'distinguishedName'; }
@{ Parameter = 'Description'; }
@{ Parameter = 'Enabled'; }
@{ Parameter = 'Manager'; ADProperty = 'managedBy'; }
)
function Get-TargetResource
{
[CmdletBinding()]
[OutputType([System.Collections.Hashtable])]
param
(
# Common Name
[Parameter(Mandatory)]
[System.String] $ComputerName,
[ValidateSet('Present', 'Absent')]
[System.String] $Ensure = 'Present',
[ValidateNotNull()]
[System.String] $UserPrincipalName,
[ValidateNotNull()]
[System.String] $DisplayName,
[ValidateNotNull()]
[System.String] $Path,
[ValidateNotNull()]
[System.String] $Location,
[ValidateNotNull()]
[System.String] $DnsHostName,
[ValidateNotNull()]
[System.String[]] $ServicePrincipalNames,
[ValidateNotNull()]
[System.String] $Description,
## Computer's manager specified as a Distinguished Name (DN)
[ValidateNotNull()]
[System.String] $Manager,
[ValidateNotNull()]
[System.String] $RequestFile,
[ValidateNotNull()]
[System.Boolean] $Enabled,
[ValidateNotNull()]
[System.String] $DomainController,
## Ideally this should just be called 'Credential' but is here for consistency with xADUser
[ValidateNotNull()]
[System.Management.Automation.PSCredential]
[System.Management.Automation.CredentialAttribute()]
$DomainAdministratorCredential,
[Parameter()]
[ValidateNotNull()]
[System.Boolean]
$CreateDisabled = $false
)
Assert-Module -ModuleName 'ActiveDirectory';
Import-Module -Name 'ActiveDirectory' -Verbose:$false;
try
{
$adCommonParameters = Get-ADCommonParameters @PSBoundParameters;
$adProperties = @();
## Create an array of the AD property names to retrieve from the property map
foreach ($property in $adPropertyMap)
{
if ($property.ADProperty)
{
$adProperties += $property.ADProperty;
}
else
{
$adProperties += $property.Parameter;
}
}
Write-Verbose -Message ($LocalizedData.RetrievingADComputer -f $ComputerName);
$adComputer = Get-ADComputer @adCommonParameters -Properties $adProperties;
Write-Verbose -Message ($LocalizedData.ADComputerIsPresent -f $ComputerName);
$Ensure = 'Present';
}
catch [Microsoft.ActiveDirectory.Management.ADIdentityNotFoundException]
{
Write-Verbose -Message ($LocalizedData.ADComputerNotPresent -f $ComputerName);
$Ensure = 'Absent';
}
catch
{
Write-Error -Message ($LocalizedData.RetrievingADComputerError -f $ComputerName);
throw $_;
}
$targetResource = @{
ComputerName = $ComputerName;
DistinguishedName = $adComputer.DistinguishedName; ## Read-only property
SID = $adComputer.SID; ## Read-only property
Ensure = $Ensure;
DomainController = $DomainController;
RequestFile = $RequestFile;
}
## Retrieve each property from the ADPropertyMap and add to the hashtable
foreach ($property in $adPropertyMap)
{
$propertyName = $property.Parameter;
if ($propertyName -eq 'Path') {
## The path returned is not the parent container
if (-not [System.String]::IsNullOrEmpty($adComputer.DistinguishedName))
{
$targetResource['Path'] = Get-ADObjectParentDN -DN $adComputer.DistinguishedName;
}
}
elseif ($property.ADProperty)
{
## The AD property name is different to the function parameter to use this
$targetResource[$propertyName] = $adComputer.($property.ADProperty);
}
else
{
## The AD property name matches the function parameter
if ($adComputer.$propertyName -is [Microsoft.ActiveDirectory.Management.ADPropertyValueCollection])
{
$targetResource[$propertyName] = $adComputer.$propertyName -as [System.String[]];
}
else
{
$targetResource[$propertyName] = $adComputer.$propertyName;
}
}
}
return $targetResource;
} #end function Get-TargetResource
function Test-TargetResource
{
[CmdletBinding()]
[OutputType([System.Boolean])]
param
(
# Common Name
[Parameter(Mandatory)]
[System.String] $ComputerName,
[ValidateSet('Present', 'Absent')]
[System.String] $Ensure = 'Present',
[ValidateNotNull()]
[System.String] $UserPrincipalName,
[ValidateNotNull()]
[System.String] $DisplayName,
[ValidateNotNull()]
[System.String] $Path,
[ValidateNotNull()]
[System.String] $Location,
[ValidateNotNull()]
[System.String] $DnsHostName,
[ValidateNotNull()]
[System.String[]] $ServicePrincipalNames,
[ValidateNotNull()]
[System.String] $Description,
## Computer's manager specified as a Distinguished Name (DN)
[ValidateNotNull()]
[System.String] $Manager,
[ValidateNotNull()]
[System.String] $RequestFile,
[ValidateNotNull()]
[System.Boolean] $Enabled,
[ValidateNotNull()]
[System.String] $DomainController,
## Ideally this should just be called 'Credential' but is here for backwards compatibility
[ValidateNotNull()]
[System.Management.Automation.PSCredential]
[System.Management.Automation.CredentialAttribute()]
$DomainAdministratorCredential,
[Parameter()]
[ValidateNotNull()]
[System.Boolean]
$CreateDisabled = $false
)
$targetResource = Get-TargetResource @PSBoundParameters;
$isCompliant = $true;
if ($Ensure -eq 'Absent')
{
if ($targetResource.Ensure -eq 'Present')
{
Write-Verbose -Message ($LocalizedData.ADComputerNotDesiredPropertyState -f `
'Ensure', $PSBoundParameters.Ensure, $targetResource.Ensure);
$isCompliant = $false;
}
}
else
{
## Add ensure and enabled as they may not be explicitly passed and we want to enumerate them
$PSBoundParameters['Ensure'] = $Ensure;
foreach ($parameter in $PSBoundParameters.Keys)
{
if ($targetResource.ContainsKey($parameter))
{
## This check is required to be able to explicitly remove values with an empty string, if required
if (([System.String]::IsNullOrEmpty($PSBoundParameters.$parameter)) -and
([System.String]::IsNullOrEmpty($targetResource.$parameter)))
{
# Both values are null/empty and therefore we are compliant
}
elseif ($parameter -eq 'ServicePrincipalNames')
{
$testMembersParams = @{
ExistingMembers = $targetResource.ServicePrincipalNames -as [System.String[]];
Members = $ServicePrincipalNames;
}
if (-not (Test-Members @testMembersParams))
{
$existingSPNs = $testMembersParams['ExistingMembers'] -join ',';
$desiredSPNs = $ServicePrincipalNames -join ',';
Write-Verbose -Message ($LocalizedData.ADComputerNotDesiredPropertyState -f `
'ServicePrincipalNames', $desiredSPNs, $existingSPNs);
$isCompliant = $false;
}
}
elseif ($PSBoundParameters.$parameter -ne $targetResource.$parameter)
{
Write-Verbose -Message ($LocalizedData.ADComputerNotDesiredPropertyState -f `
$parameter, $PSBoundParameters.$parameter, $targetResource.$parameter);
$isCompliant = $false;
}
}
} #end foreach PSBoundParameter
}
if ($isCompliant)
{
Write-Verbose -Message ($LocalizedData.ADComputerInDesiredState -f $ComputerName)
return $true
}
else
{
Write-Verbose -Message ($LocalizedData.ADComputerNotInDesiredState -f $ComputerName)
return $false
}
} #end function Test-TargetResource
function Set-TargetResource
{
[CmdletBinding()]
param
(
# Common Name
[Parameter(Mandatory)]
[System.String] $ComputerName,
[ValidateSet('Present', 'Absent')]
[System.String] $Ensure = 'Present',
[ValidateNotNull()]
[System.String] $UserPrincipalName,
[ValidateNotNull()]
[System.String] $DisplayName,
[ValidateNotNull()]
[System.String] $Path,
[ValidateNotNull()]
[System.String] $Location,
[ValidateNotNull()]
[System.String] $DnsHostName,
[ValidateNotNull()]
[System.String[]] $ServicePrincipalNames,
[ValidateNotNull()]
[System.String] $Description,
## Computer's manager specified as a Distinguished Name (DN)
[ValidateNotNull()]
[System.String] $Manager,
[ValidateNotNull()]
[System.String] $RequestFile,
[ValidateNotNull()]
[System.Boolean] $Enabled,
[ValidateNotNull()]
[System.String] $DomainController,
## Ideally this should just be called 'Credential' but is here for backwards compatibility
[ValidateNotNull()]
[System.Management.Automation.PSCredential]
[System.Management.Automation.CredentialAttribute()]
$DomainAdministratorCredential,
[Parameter()]
[ValidateNotNull()]
[System.Boolean]
$CreateDisabled = $false
)
$targetResource = Get-TargetResource @PSBoundParameters;
## Add ensure as they may not be explicitly passed and we want to enumerate them
$PSBoundParameters['Ensure'] = $Ensure;
if ($Ensure -eq 'Present')
{
if ($targetResource.Ensure -eq 'Absent') {
## Computer does not exist and needs creating
if ($RequestFile)
{
## Use DJOIN to create the computer account as well as the ODJ Request file.
Write-Verbose -Message ($LocalizedData.ODJRequestStartMessage -f `
$DomainName,$ComputerName,$RequestFile)
# This should only be performed on a Domain Member, so detect the Domain Name.
$DomainName = Get-DomainName
$DJoinParameters = @(
'/PROVISION'
'/DOMAIN',$DomainName
'/MACHINE',$ComputerName )
if ($PSBoundParameters.ContainsKey('Path'))
{
$DJoinParameters += @( '/MACHINEOU',$Path )
} # if
if ($PSBoundParameters.ContainsKey('DomainController'))
{
$DJoinParameters += @( '/DCNAME',$DomainController )
} # if
$DJoinParameters += @( '/SAVEFILE',$RequestFile )
$Result = & djoin.exe @DjoinParameters
if ($LASTEXITCODE -ne 0)
{
$errorId = 'ODJRequestError'
$errorMessage = $($LocalizedData.ODJRequestError `
-f $LASTEXITCODE,$Result)
ThrowInvalidOperationError -ErrorId $errorId -ErrorMessage $errorMessage
} # if
Write-Verbose -Message ($LocalizedData.ODJRequestCompleteMessage -f `
$DomainName,$ComputerName,$RequestFile)
}
else
{
## Create the computer account using New-ADComputer
$newADComputerParams = Get-ADCommonParameters @PSBoundParameters -UseNameParameter;
if ($PSBoundParameters.ContainsKey('Path'))
{
Write-Verbose -Message ($LocalizedData.UpdatingADComputerProperty -f 'Path', $Path);
$newADComputerParams['Path'] = $Path;
}
<#
If CreateDisabled is set to $true, or Enabled is set to $false,
then create the computer account disabled.
If not then create the computer account enabled.
#>
if (
($CreateDisabled -and -not $PSBoundParameters.ContainsKey('Enabled')) `
-or ($PSBoundParameters.ContainsKey('Enabled') -and -not $Enabled)
)
{
Write-Verbose -Message ($LocalizedData.AddingADComputerAsDisabled -f $ComputerName);
$newADComputerParams['Enabled'] = $false;
}
else
{
Write-Verbose -Message ($LocalizedData.AddingADComputer -f $ComputerName);
$newADComputerParams['Enabled'] = $true;
}
New-ADComputer @newADComputerParams;
} # if
## Now retrieve the newly created computer
$targetResource = Get-TargetResource @PSBoundParameters;
}
$setADComputerParams = Get-ADCommonParameters @PSBoundParameters;
$replaceComputerProperties = @{};
$removeComputerProperties = @{};
foreach ($parameter in $PSBoundParameters.Keys)
{
## Only check/action properties specified/declared parameters that match one of the function's
## parameters. This will ignore common parameters such as -Verbose etc.
if ($targetResource.ContainsKey($parameter))
{
if ($parameter -eq 'Path' -and ($PSBoundParameters.Path -ne $targetResource.Path))
{
## Cannot move computers by updating the DistinguishedName property
$adCommonParameters = Get-ADCommonParameters @PSBoundParameters;
## Using the SamAccountName for identity with Move-ADObject does not work, use the DN instead
$adCommonParameters['Identity'] = $targetResource.DistinguishedName;
Write-Verbose -Message ($LocalizedData.MovingADComputer -f `
$targetResource.Path, $PSBoundParameters.Path);
Move-ADObject @adCommonParameters -TargetPath $PSBoundParameters.Path;
}
elseif ($parameter -eq 'ServicePrincipalNames')
{
Write-Verbose -Message ($LocalizedData.UpdatingADComputerProperty -f `
'ServicePrincipalNames', ($ServicePrincipalNames -join ','));
$replaceComputerProperties['ServicePrincipalName'] = $ServicePrincipalNames;
}
elseif ($parameter -eq 'Enabled' -and ($PSBoundParameters.$parameter -ne $targetResource.$parameter))
{
Write-Verbose -Message ($LocalizedData.UpdatingADComputerProperty -f `
$parameter, $PSBoundParameters.$parameter);
<#
The Enabled property cannot be set as a hash table value in the
Remove or Replace parameter of the Set-ADComputer cmdlet. So
adding it as a parameter to the Set-ADComputer cmdlet.
#>
$setADComputerParams['Enabled'] = $PSBoundParameters.$parameter
}
elseif ($PSBoundParameters.$parameter -ne $targetResource.$parameter)
{
## Find the associated AD property
$adProperty = $adPropertyMap | Where-Object { $_.Parameter -eq $parameter };
if ([System.String]::IsNullOrEmpty($adProperty))
{
## We can't do anything with an empty AD property!
}
elseif ([System.String]::IsNullOrEmpty($PSBoundParameters.$parameter))
{
## We are removing properties
## Only remove if the existing value in not null or empty
if (-not ([System.String]::IsNullOrEmpty($targetResource.$parameter)))
{
Write-Verbose -Message ($LocalizedData.RemovingADComputerProperty -f `
$parameter, $PSBoundParameters.$parameter);
if ($adProperty.UseCmdletParameter -eq $true)
{
## We need to pass the parameter explicitly to Set-ADComputer, not via -Remove
$setADComputerParams[$adProperty.Parameter] = $PSBoundParameters.$parameter;
}
elseif ([System.String]::IsNullOrEmpty($adProperty.ADProperty))
{
$removeComputerProperties[$adProperty.Parameter] = $targetResource.$parameter;
}
else
{
$removeComputerProperties[$adProperty.ADProperty] = $targetResource.$parameter;
}
}
} #end if remove existing value
else
{
## We are replacing the existing value
Write-Verbose -Message ($LocalizedData.UpdatingADComputerProperty -f `
$parameter, $PSBoundParameters.$parameter);
if ($adProperty.UseCmdletParameter -eq $true)
{
## We need to pass the parameter explicitly to Set-ADComputer, not via -Replace
$setADComputerParams[$adProperty.Parameter] = $PSBoundParameters.$parameter;
}
elseif ([System.String]::IsNullOrEmpty($adProperty.ADProperty))
{
$replaceComputerProperties[$adProperty.Parameter] = $PSBoundParameters.$parameter;
}
else
{
$replaceComputerProperties[$adProperty.ADProperty] = $PSBoundParameters.$parameter;
}
} #end if replace existing value
}
} #end if TargetResource parameter
} #end foreach PSBoundParameter
<#
Set-ADComputer is only called if we have something to change, or
$setADComputerParams contains more than one value (ignoring parameter
'Identity' by itself).
#>
if ($replaceComputerProperties.Count -or $removeComputerProperties.Count -or $setADComputerParams.Count -gt 1)
{
## Only pass -Remove and/or -Replace if we have something to set/change
if ($replaceComputerProperties.Count -gt 0)
{
$setADComputerParams['Replace'] = $replaceComputerProperties;
}
if ($removeComputerProperties.Count -gt 0)
{
$setADComputerParams['Remove'] = $removeComputerProperties;
}
Write-Verbose -Message ($LocalizedData.UpdatingADComputer -f $ComputerName);
Set-DscADComputer -SetADComputerParameters $setADComputerParams
}
}
elseif (($Ensure -eq 'Absent') -and ($targetResource.Ensure -eq 'Present'))
{
## User exists and needs removing
Write-Verbose ($LocalizedData.RemovingADComputer -f $ComputerName);
$adCommonParameters = Get-ADCommonParameters @PSBoundParameters;
[ref] $null = Remove-ADComputer @adCommonParameters -Confirm:$false;
}
} #end function Set-TargetResource
## Import the common AD functions
$adCommonFunctions = Join-Path `
-Path (Split-Path -Path $PSScriptRoot -Parent) `
-ChildPath '\MSFT_xADCommon\MSFT_xADCommon.ps1';
. $adCommonFunctions;
<#
.SYNOPSIS
This is a wrapper for Set-ADComputer. This is needed because of
how Pester is unable to handle mocking this cmdlet.
.PARAMETER SetADComputerParameters
A hash table containing all parameters that will be pass trough to
Set-ADComputer.
#>
function Set-DscADComputer
{
param
(
[Parameter()]
[System.Collections.Hashtable]
$SetADComputerParameters
)
[ref] $null = Set-ADComputer @SetADComputerParameters
}
Export-ModuleMember -Function *-TargetResource