-
Notifications
You must be signed in to change notification settings - Fork 132
/
MSFT_xGroupResource.psm1
2572 lines (2133 loc) · 86.9 KB
/
MSFT_xGroupResource.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
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
<#
Implementatation Notes
Managing Disposable Objects
The types PrincipalContext, Principal, and DirectoryEntry are used througout the code and
all are disposable. However, in many cases, disposing the object immediately causes
subsequent operations to fail or duplicate disposes calls to occur.
To simplify management of these disposables, each public entry point defines a $disposables
ArrayList variable and passes it to secondary functions that may need to create disposable
objects. The public entry point is then required to dispose the contents of the list in a
finally block.
Managing PrincipalContext Instances
To use the AccountManagement APIs to connect to the local machine or a domain, a
PrincipalContext is needed.
For the local groups and users, a PrincipalContext reflecting the current user can be
created.
For the default domain, the domain where the machine is joined, explicit credentials are
needed since the default user context is SYSTEM which has no rights to the domain.
Additional PrincipalContext instances may be needed when the machine is in a domain that is
part of a multi-domain forest. For example, Microsoft uses a multi-domain forest that
includes domains such as ntdev, redmond, wingroup and a group may have members that
span multiple domains. Unless the enterprise implements the Global Catalog,
something that Microsoft does not do, a unique PrincipalContext is needed to resolve
accounts in each of the domains.
To manage the use of PrincipalContext across domains, public entry points define a
$principalContextCache hashtable and pass it to support functions that need to resolve a group
or group member. Consumers of a PrincipalContext call Get-PrincipalContext with a scope
(domain name or machine name). Get-PrincipalContext returns an existing hashtable entry or
creates a new entry. Note that a PrincipalContext to a target domain requires connecting
to the domain. The hashtable avoids subsequent connection calls. Also note that
Get-PrincipalContext takes a Credential parameter for the case where a new PrincipalContext
is needed. The implicit assumption is that the credential provided for the primary domain
also has rights to resolve accounts in any of the other domains.
Resolving Group Members
The original implementation assumed that group members could be resolved using the machine
PrincipalContext or the logged on user. In practice this is not reliable since the resource
is typically run under the SYSTEM account and this account is not guaranteed to have rights
to resolve domain accounts. Additionally, the APIs for enumerating group members do not
provide a facility for passing additional credentials resulting in domain members failing
to resolve.
To address this, group members are enumerated by first converting the GroupPrincipal to a
DirectoryEntry and enumerating its child members. The returned DirectoryEntry instances are
then resolved to Principal objects using a PrincipalContext appropriate for the target
domain.
Handling Stale Group Members
A group may have stale members if the machine was moved from one domain to a another
foreign domain or when accounts are deleted (domain or local). At this point, members that
were defined in the original domain or were deleted are now stale and cannot be resolved
using Principal::FindByIdentity. The original implementation failed at this point
preventing any operations against the group. The current implementation calls Write-Warning
with the associated SID of the member that cannot be resolved then continues the operation.
#>
$errorActionPreference = 'Stop'
Set-StrictMode -Version 'Latest'
# Import CommonResourceHelper for Test-IsNanoServer
$script:dscResourcesFolderFilePath = Split-Path $PSScriptRoot -Parent
$script:commonResourceHelperFilePath = Join-Path -Path $script:dscResourcesFolderFilePath -ChildPath 'CommonResourceHelper.psm1'
Import-Module -Name $script:commonResourceHelperFilePath
$script:localizedData = Get-LocalizedData -ResourceName 'MSFT_xGroupResource'
if (-not (Test-IsNanoServer))
{
Add-Type -AssemblyName 'System.DirectoryServices.AccountManagement'
}
<#
.SYNOPSIS
Retrieves the current state of the group with the specified name.
.PARAMETER GroupName
The name of the group to retrieve the current state of.
.PARAMETER Credential
A credential to resolve non-local group members.
#>
function Get-TargetResource
{
[OutputType([Hashtable])]
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$GroupName,
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential
)
Assert-GroupNameValid -GroupName $GroupName
if (Test-IsNanoServer)
{
Write-Verbose -Message ($script:localizedData.InvokingFunctionForGroup -f 'Get-TargetResourceOnNanoServer', $GroupName)
return Get-TargetResourceOnNanoServer @PSBoundParameters
}
else
{
Write-Verbose -Message ($script:localizedData.InvokingFunctionForGroup -f 'Get-TargetResourceOnFullSKU', $GroupName)
return Get-TargetResourceOnFullSKU @PSBoundParameters
}
}
<#
.SYNOPSIS
Creates, modifies, or removes a group.
.PARAMETER GroupName
The name of the group to create, modify, or remove.
.PARAMETER Ensure
Specifies whether the group should exist or not.
To ensure that the group does exist, set this property to present.
To ensure that the group does not exist, set this property to Absent.
The default value is Present.
.PARAMETER Description
The description the group should have.
.PARAMETER Members
The members the group should have.
This property will replace all the current group members with the specified members.
Members should be specified as strings in the format of their domain qualified name
(domain\username), their UPN (username@domainname), their distinguished name (CN=username,DC=...),
or their username (for local machine accounts).
Using either the MembersToExclude or MembersToInclude properties in the same configuration
as this property will generate an error.
.PARAMETER MembersToInclude
The members the group should include.
This property will only add members to a group.
Members should be specified as strings in the format of their domain qualified name
(domain\username), their UPN (username@domainname), their distinguished name (CN=username,DC=...),
or their username (for local machine accounts).
Using the Members property in the same configuration as this property will generate an error.
.PARAMETER MembersToExclude
The members the group should exclude.
This property will only remove members from a group.
Members should be specified as strings in the format of their domain qualified name
(domain\username), their UPN (username@domainname), their distinguished name (CN=username,DC=...),
or their username (for local machine accounts).
Using the Members property in the same configuration as this property will generate an error.
.PARAMETER Credential
A credential to resolve and add non-local group members.
An error will occur if this account does not have the appropriate Active Directory permissions to add all
non-local accounts to the group.
.NOTES
ShouldProcess PSSA rule is suppressed because Set-TargetResourceOnFullSKU and
Set-TargetResourceOnNanoServer call ShouldProcess.
#>
function Set-TargetResource
{
[Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSShouldProcess', '')]
[CmdletBinding(SupportsShouldProcess = $true)]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$GroupName,
[ValidateSet('Present', 'Absent')]
[String]
$Ensure = 'Present',
[String]
$Description,
[String[]]
$Members,
[String[]]
$MembersToInclude,
[String[]]
$MembersToExclude,
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential
)
Write-Verbose ($script:localizedData.SetTargetResourceStartMessage -f $GroupName)
Assert-GroupNameValid -GroupName $GroupName
if (Test-IsNanoServer)
{
Set-TargetResourceOnNanoServer @PSBoundParameters
}
else
{
Set-TargetResourceOnFullSKU @PSBoundParameters
}
Write-Verbose ($script:localizedData.SetTargetResourceEndMessage -f $GroupName)
}
<#
.SYNOPSIS
Tests if the group with the specified name is in the desired state.
.PARAMETER GroupName
The name of the group to test the state of.
.PARAMETER Ensure
Indicates if the group should exist or not.
Set this property to "Absent" to test that the group does not exist.
Setting it to "Present" (the default value) tests that the group exists.
.PARAMETER Description
The description of the group to test for.
.PARAMETER Members
The list of members the group should have.
The value of this property is an array of strings of the formats domain qualified name
(domain\username), UPN (username@domainname), distinguished name (CN=username,DC=...) and/or
a unqualified (username) for local machine accounts.
If you set this property in a configuration, do not use either the MembersToExclude or
MembersToInclude property. Doing so will generate an error.
.PARAMETER MembersToInclude
A list of members that should be in the group.
The value of this property is an array of strings of the formats domain qualified name
(domain\username), UPN (username@domainname), distinguished name (CN=username,DC=...) and/or
a unqualified (username) for local machine accounts.
If you set this property in a configuration, do not use the Members property.
Doing so will generate an error.
.PARAMETER MembersToExclude
A list of members that should not be in the group.
The value of this property is an array of strings of the formats domain qualified name
(domain\username), UPN (username@domainname), distinguished name (CN=username,DC=...) and/or
a unqualified (username) for local machine accounts.
If you set this property in a configuration, do not use the Members property.
Doing so will generate an error.
.PARAMETER Credential
The credentials required to resolve non-local group members
#>
function Test-TargetResource
{
[OutputType([Boolean])]
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$GroupName,
[ValidateSet('Present', 'Absent')]
[String]
$Ensure = 'Present',
[String]
$Description,
[String[]]
$Members,
[String[]]
$MembersToInclude,
[String[]]
$MembersToExclude,
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential
)
Assert-GroupNameValid -GroupName $GroupName
if (Test-IsNanoServer)
{
Write-Verbose ($script:localizedData.InvokingFunctionForGroup -f 'Test-TargetResourceOnNanoServer', $GroupName)
return Test-TargetResourceOnNanoServer @PSBoundParameters
}
else
{
Write-Verbose ($script:localizedData.InvokingFunctionForGroup -f 'Test-TargetResourceOnFullSKU', $GroupName)
return Test-TargetResourceOnFullSKU @PSBoundParameters
}
}
<#
.SYNOPSIS
Retrieves the current state of the group with the specified name on a full server.
.PARAMETER GroupName
The name of the group to retrieve the current state of.
.PARAMETER Credential
A credential to resolve non-local group members.
#>
function Get-TargetResourceOnFullSKU
{
[OutputType([Hashtable])]
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$GroupName,
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential
)
$principalContextCache = @{}
$disposables = New-Object -TypeName 'System.Collections.ArrayList'
try
{
$principalContext = Get-PrincipalContext `
-PrincipalContextCache $principalContextCache `
-Disposables $Disposables `
-Scope $env:COMPUTERNAME
$group = Get-Group -GroupName $GroupName -PrincipalContext $principalContext
if ($null -ne $group)
{
$null = $disposables.Add($group)
# The group was found. Find the group members.
$members = Get-MembersOnFullSKU -Group $group -PrincipalContextCache $principalContextCache `
-Credential $Credential -Disposables $disposables
return @{
GroupName = $group.Name
Ensure = 'Present'
Description = $group.Description
Members = $members
}
}
else
{
# The group was not found.
return @{
GroupName = $GroupName
Ensure = 'Absent'
}
}
}
finally
{
Remove-DisposableObject -Disposables $disposables
}
}
<#
.SYNOPSIS
Retrieves the current state of the group with the specified name on Nano Server.
.PARAMETER GroupName
The name of the group to retrieve the current state of.
.PARAMETER Credential
A credential to resolve non-local group members.
#>
function Get-TargetResourceOnNanoServer
{
[OutputType([Hashtable])]
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$GroupName,
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential
)
try
{
$group = Get-LocalGroup -Name $GroupName -ErrorAction 'Stop'
}
catch
{
if ($_.CategoryInfo.Reason -eq 'GroupNotFoundException')
{
# The group was not found.
return @{
GroupName = $GroupName
Ensure = 'Absent'
}
}
New-InvalidOperationException -ErrorRecord $_
}
# The group was found. Find the group members.
$members = Get-MembersOnNanoServer -Group $group
return @{
GroupName = $group.Name
Ensure = 'Present'
Description = $group.Description
Members = $members
}
}
<#
.SYNOPSIS
The Set-TargetResource cmdlet on a full server.
.PARAMETER GroupName
The name of the group for which you want to ensure a specific state.
.PARAMETER Ensure
Indicates if the group should exist or not.
Set this property to Present to ensure that the group exists.
Set this property to Absent to ensure that the group does not exist.
The default value is Present.
.PARAMETER Description
The description of the group.
.PARAMETER Members
Use this property to replace the current group membership with the specified members.
The value of this property is an array of strings of the formats domain qualified name
(domain\username), UPN (username@domainname), distinguished name (CN=username,DC=...) and/or
an unqualified (username) for local machine accounts.
If you set this property in a configuration, do not use either the MembersToExclude or
MembersToInclude property. Doing so will generate an error.
.PARAMETER MembersToInclude
Use this property to add members to the existing membership of the group.
The value of this property is an array of strings of the formats domain qualified name
(domain\username), UPN (username@domainname), distinguished name (CN=username,DC=...) and/or
a unqualified (username) for local machine accounts.
If you set this property in a configuration, do not use the Members property.
Doing so will generate an error.
.PARAMETER MembersToExclude
Use this property to remove members from the existing membership of the group.
The value of this property is an array of strings of the formats domain qualified name
(domain\username), UPN (username@domainname), distinguished name (CN=username,DC=...) and/or
a unqualified (username) for local machine accounts.
If you set this property in a configuration, do not use the Members property.
Doing so will generate an error.
.PARAMETER Credential
The credentials required to access remote resources. Note: This account must have the
appropriate Active Directory permissions to add all non-local accounts to the group.
Otherwise, an error will occur.
#>
function Set-TargetResourceOnFullSKU
{
[CmdletBinding(SupportsShouldProcess = $true)]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$GroupName,
[ValidateSet('Present', 'Absent')]
[String]
$Ensure = 'Present',
[String]
$Description,
[String[]]
$Members,
[String[]]
$MembersToInclude,
[String[]]
$MembersToExclude,
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential
)
$principalContextCache = @{}
$disposables = New-Object -TypeName 'System.Collections.ArrayList'
try
{
$principalContext = Get-PrincipalContext `
-PrincipalContextCache $principalContextCache `
-Disposables $disposables `
-Scope $env:computerName
# Try to find a group by its name.
$group = Get-Group -GroupName $GroupName -PrincipalContext $principalContext
$groupOriginallyExists = $null -ne $group
if ($Ensure -eq 'Present')
{
$shouldProcessTarget = $script:localizedData.GroupWithName -f $GroupName
if ($groupOriginallyExists)
{
$null = $disposables.Add($group)
$whatIfShouldProcess = $PSCmdlet.ShouldProcess($shouldProcessTarget, $script:localizedData.SetOperation)
}
else
{
$whatIfShouldProcess = $PSCmdlet.ShouldProcess($shouldProcessTarget, $script:localizedData.AddOperation)
}
if ($whatIfShouldProcess)
{
$saveChanges = $false
if (-not $groupOriginallyExists)
{
$localPrincipalContext = Get-PrincipalContext -PrincipalContextCache $principalContextCache `
-Disposables $disposables -Scope $env:COMPUTERNAME
$group = New-Object -TypeName 'System.DirectoryServices.AccountManagement.GroupPrincipal' `
-ArgumentList @( $localPrincipalContext )
$null = $disposables.Add($group)
$group.Name = $GroupName
$saveChanges = $true
}
# Set group properties.
if ($PSBoundParameters.ContainsKey('Description') -and $Description -ne $group.Description)
{
$group.Description = $Description
$saveChanges = $true
}
$actualMembersAsPrincipals = $null
<#
Group members can be updated in two ways:
1. Supplying the Members parameter - this causes the membership to be replaced
with the members defined in Members.
NOTE: If Members is empty, the group membership is cleared.
2. Providing MembersToInclude and/or MembersToExclude
- this adds/removes members from the list.
If Members is mutually exclusive with MembersToInclude and MembersToExclude
If Members is not defined then MembersToInclude or MembersToExclude
must contain at least one entry.
#>
if ($PSBoundParameters.ContainsKey('Members'))
{
foreach ($incompatibleParameterName in @( 'MembersToInclude', 'MembersToExclude' ))
{
if ($PSBoundParameters.ContainsKey($incompatibleParameterName))
{
New-InvalidArgumentException -ArgumentName $incompatibleParameterName `
-Message ($script:localizedData.MembersAndIncludeExcludeConflict -f 'Members', $incompatibleParameterName)
}
}
if ($groupOriginallyExists)
{
$actualMembersAsPrincipals = @( Get-MembersAsPrincipalsList `
-Group $group `
-PrincipalContextCache $principalContextCache `
-Disposables $disposables `
-Credential $Credential
)
}
if ($Members.Count -eq 0 -and $null -ne $actualMembersAsPrincipals -and $actualMembersAsPrincipals.Count -ne 0)
{
Clear-GroupMembers -Group $group
$saveChanges = $true
}
elseif ($Members.Count -ne 0)
{
# Remove duplicate names as strings.
$uniqueMembers = $Members | Select-Object -Unique
# Resolve the names to actual principal objects.
$membersAsPrincipals = @( ConvertTo-UniquePrincipalsList `
-MemberNames $uniqueMembers `
-PrincipalContextCache $principalContextCache `
-Disposables $disposables `
-Credential $Credential )
if ($null -ne $actualMembersAsPrincipals -and $actualMembersAsPrincipals.Count -gt 0)
{
foreach ($memberAsPrincipal in $membersAsPrincipals)
{
if ($actualMembersAsPrincipals -notcontains $memberAsPrincipal)
{
Add-GroupMember -Group $group -MemberAsPrincipal $memberAsPrincipal
$saveChanges = $true
}
}
foreach ($actualMemberAsPrincipal in $actualMembersAsPrincipals)
{
if ($membersAsPrincipals -notcontains $actualMemberAsPrincipal)
{
Remove-GroupMember -Group $group -MemberAsPrincipal $actualMemberAsPrincipal
$saveChanges = $true
}
}
}
else
{
# Set the members of the group
foreach ($memberAsPrincipal in $membersAsPrincipals)
{
Add-GroupMember -Group $group -MemberAsPrincipal $memberAsPrincipal
}
$saveChanges = $true
}
}
else
{
Write-Verbose -Message ($script:localizedData.GroupAndMembersEmpty -f $GroupName)
}
}
elseif ($PSBoundParameters.ContainsKey('MembersToInclude') -or $PSBoundParameters.ContainsKey('MembersToExclude'))
{
if ($groupOriginallyExists)
{
$actualMembersAsPrincipals = @( Get-MembersAsPrincipalsList `
-Group $group `
-PrincipalContextCache $principalContextCache `
-Disposables $disposables `
-Credential $Credential
)
}
$membersToIncludeAsPrincipals = $null
$uniqueMembersToInclude = $MembersToInclude | Select-Object -Unique
if ($null -eq $uniqueMembersToInclude)
{
Write-Verbose -Message $script:localizedData.MembersToIncludeEmpty
}
else
{
# Resolve the names to actual principal objects.
$membersToIncludeAsPrincipals = @( ConvertTo-UniquePrincipalsList `
-MemberNames $uniqueMembersToInclude `
-PrincipalContextCache $principalContextCache `
-Disposables $disposables `
-Credential $Credential
)
}
$membersToExcludeAsPrincipals = $null
$uniqueMembersToExclude = $MembersToExclude | Select-Object -Unique
if ($null -eq $uniqueMembersToExclude)
{
Write-Verbose -Message $script:localizedData.MembersToExcludeEmpty
}
else
{
# Resolve the names to actual principal objects.
$membersToExcludeAsPrincipals = @( ConvertTo-UniquePrincipalsList `
-MemberNames $uniqueMembersToExclude `
-PrincipalContextCache $principalContextCache `
-Disposables $disposables `
-Credential $Credential
)
}
foreach ($includedPrincipal in $membersToIncludeAsPrincipals)
{
<#
Throw an error if any common principals were provided in MembersToInclude
and MembersToExclude.
#>
if ($membersToExcludeAsPrincipals -contains $includedPrincipal)
{
New-InvalidArgumentException -ArgumentName 'MembersToInclude and MembersToExclude' `
-Message ($script:localizedData.IncludeAndExcludeConflict -f $includedPrincipal.SamAccountName,
'MembersToInclude', 'MembersToExclude')
}
if ($actualMembersAsPrincipals -notcontains $includedPrincipal)
{
Add-GroupMember -Group $group -MemberAsPrincipal $includedPrincipal
$saveChanges = $true
}
}
foreach ($excludedPrincipal in $membersToExcludeAsPrincipals)
{
if ($actualMembersAsPrincipals -contains $excludedPrincipal)
{
Remove-GroupMember -Group $group -MemberAsPrincipal $excludedPrincipal
$saveChanges = $true
}
}
}
if ($saveChanges)
{
Save-Group -Group $group
# Send an operation success verbose message.
if ($groupOriginallyExists)
{
Write-Verbose -Message ($script:localizedData.GroupUpdated -f $GroupName)
}
else
{
Write-Verbose -Message ($script:localizedData.GroupCreated -f $GroupName)
}
}
else
{
Write-Verbose -Message ($script:localizedData.NoConfigurationRequired -f $GroupName)
}
}
}
else
{
if ($groupOriginallyExists)
{
if ($PSCmdlet.ShouldProcess(($script:localizedData.GroupWithName -f $GroupName), $script:localizedData.RemoveOperation))
{
# Don't add group to $disposables since Delete also disposes.
Remove-Group -Group $group
Write-Verbose -Message ($script:localizedData.GroupRemoved -f $GroupName)
}
else
{
$null = $disposables.Add($group)
}
}
else
{
Write-Verbose -Message ($script:localizedData.NoConfigurationRequiredGroupDoesNotExist -f $GroupName)
}
}
}
finally
{
Remove-DisposableObject -Disposables $disposables
}
}
<#
.SYNOPSIS
The Set-TargetResource cmdlet on Nano Server.
.PARAMETER GroupName
The name of the group for which you want to ensure a specific state.
.PARAMETER Ensure
Indicates if the group should exist or not.
Set this property to Present to ensure that the group exists.
Set this property to Absent to ensure that the group does not exist.
The default value is Present.
.PARAMETER Description
The description of the group.
.PARAMETER Members
Use this property to replace the current group membership with the specified members.
The value of this property is an array of strings of the formats domain qualified name
(domain\username), UPN (username@domainname), distinguished name (CN=username,DC=...) and/or
a unqualified (username) for local machine accounts.
If you set this property in a configuration, do not use either the MembersToExclude or
MembersToInclude property. Doing so will generate an error.
.PARAMETER MembersToInclude
Use this property to add members to the existing membership of the group.
The value of this property is an array of strings of the formats domain qualified name
(domain\username), UPN (username@domainname), distinguished name (CN=username,DC=...) and/or
a unqualified (username) for local machine accounts.
If you set this property in a configuration, do not use the Members property.
Doing so will generate an error.
.PARAMETER MembersToExclude
Use this property to remove members from the existing membership of the group.
The value of this property is an array of strings of the formats domain qualified name
(domain\username), UPN (username@domainname), distinguished name (CN=username,DC=...) and/or
a unqualified (username) for local machine accounts.
If you set this property in a configuration, do not use the Members property.
Doing so will generate an error.
.PARAMETER Credential
Not used on Nano Server.
Only local users are accessible from the resource.
#>
function Set-TargetResourceOnNanoServer
{
[CmdletBinding(SupportsShouldProcess = $true)]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[String]
$GroupName,
[ValidateSet('Present', 'Absent')]
[String]
$Ensure = 'Present',
[String]
$Description,
[String[]]
$Members,
[String[]]
$MembersToInclude,
[String[]]
$MembersToExclude,
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential
)
try
{
$group = Get-LocalGroup -Name $GroupName -ErrorAction 'Stop'
$groupOriginallyExists = $true
}
catch [System.Exception]
{
if ($_.CategoryInfo.Reason -eq 'GroupNotFoundException')
{
# A group with the provided name does not exist.
Write-Verbose -Message ($script:localizedData.GroupDoesNotExist -f $GroupName)
$groupOriginallyExists = $false
}
else
{
New-InvalidOperationException -ErrorRecord $_
}
}
if ($Ensure -eq 'Present')
{
$whatIfShouldProcess =
if ($groupOriginallyExists)
{
$PSCmdlet.ShouldProcess(($script:localizedData.GroupWithName -f $GroupName),
$script:localizedData.SetOperation)
}
else
{
$PSCmdlet.ShouldProcess(($script:localizedData.GroupWithName -f $GroupName),
$script:localizedData.AddOperation)
}
if ($whatIfShouldProcess)
{
if (-not $groupOriginallyExists)
{
$group = New-LocalGroup -Name $GroupName
Write-Verbose -Message ($script:localizedData.GroupCreated -f $GroupName)
}
# Set the group properties.
if ($PSBoundParameters.ContainsKey('Description') -and
((-not $groupOriginallyExists) -or ($Description -ne $group.Description)))
{
Set-LocalGroup -Name $GroupName -Description $Description
}
if ($PSBoundParameters.ContainsKey('Members'))
{
foreach ($incompatibleParameterName in @( 'MembersToInclude', 'MembersToExclude' ))
{
if ($PSBoundParameters.ContainsKey($incompatibleParameterName))
{
New-InvalidArgumentException -ArgumentName $incompatibleParameterName `
-Message ($script:localizedData.MembersAndIncludeExcludeConflict -f 'Members', $incompatibleParameterName)
}
}
$groupMembers = Get-MembersOnNanoServer -Group $group
# Remove duplicate names as strings.
$uniqueMembers = $Members | Select-Object -Unique
# Remove unspecified members
foreach ($groupMember in $groupMembers)
{
if ($uniqueMembers -notcontains $groupMember)
{
Remove-LocalGroupMember -Group $GroupName -Member $groupMember
}
}
# Add specified missing members
foreach ($uniqueMember in $uniqueMembers)
{
if ($groupMembers -notcontains $uniqueMember)
{
Add-LocalGroupMember -Group $GroupName -Member $uniqueMember
}
}
}
elseif ($PSBoundParameters.ContainsKey('MembersToInclude') -or $PSBoundParameters.ContainsKey('MembersToExclude'))
{
[array]$groupMembers = Get-MembersOnNanoServer -Group $group
$uniqueMembersToInclude = $MembersToInclude | Select-Object -Unique
$uniqueMembersToExclude = $MembersToExclude | Select-Object -Unique
<#
Both MembersToInclude and MembersToExclude were provided.
Check if they have common principals.
#>
foreach ($includedMember in $uniqueMembersToInclude)
{
foreach($excludedMember in $uniqueMembersToExclude)
{
if ($includedMember -eq $excludedMember)
{
New-InvalidArgumentException -ArgumentName 'MembersToInclude and MembersToExclude' `
-Message ($script:localizedData.IncludeAndExcludeConflict -f $includedMember, 'MembersToInclude',
'MembersToExclude')
}
}
}
foreach ($includedMember in $uniqueMembersToInclude)
{
if ($groupMembers -notcontains $includedMember)
{
Add-LocalGroupMember -Group $GroupName -Member $includedMember
}
}
foreach($excludedMember in $uniqueMembersToExclude)
{
if ($groupMembers -contains $excludedMember)