-
Notifications
You must be signed in to change notification settings - Fork 134
/
DSC_xServiceResource.psm1
1862 lines (1540 loc) · 61.6 KB
/
DSC_xServiceResource.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
<#
Error codes and their meanings for Invoke-CimMethod on a Win32_Service can be found here:
https://msdn.microsoft.com/en-us/library/aa384901(v=vs.85).aspx
#>
$errorActionPreference = 'Stop'
Set-StrictMode -Version 'Latest'
$modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules'
# Import the shared modules
Import-Module -Name (Join-Path -Path $modulePath `
-ChildPath (Join-Path -Path 'xPSDesiredStateConfiguration.Common' `
-ChildPath 'xPSDesiredStateConfiguration.Common.psm1'))
Import-Module -Name (Join-Path -Path $modulePath -ChildPath 'DscResource.Common')
# Import Localization Strings
$script:localizedData = Get-LocalizedData -DefaultUICulture 'en-US'
<#
.SYNOPSIS
Retrieves the current status of the service resource with the given name.
.PARAMETER Name
The name of the service to retrieve the status of.
This may be different from the service's display name.
To retrieve a list of all services with their names and current states, use the Get-Service
cmdlet.
.NOTES
BuiltInAccount, Credential and GroupManagedServiceAccount parameters output the user used
to run the service to the BuiltinAccount property, Evaluating if the account is a gMSA would
mean doing a call to active directory to verify, as the property returned by the ciminstance
is just a string. In a production scenario that would mean that every xService test will check
with AD every 15 minutes if the account is a gMSA. That's not desireable, so we output Credential
and GroupManagedServiceAccount without evaluating what kind of user is supplied.
#>
function Get-TargetResource
{
[OutputType([System.Collections.Hashtable])]
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$Name
)
$service = Get-Service -Name $Name -ErrorAction 'SilentlyContinue'
if ($null -ne $service)
{
Write-Verbose -Message ($script:localizedData.ServiceExists -f $Name)
$serviceCimInstance = Get-ServiceCimInstance -ServiceName $Name
$dependencies = @()
foreach ($serviceDependedOn in $service.ServicesDependedOn)
{
if ($null -ne $serviceDependedOn -and $null -ne $serviceDependedOn.Name)
{
$dependencies += $serviceDependedOn.Name.ToString()
}
else
{
Write-Warning -Message ($script:localizedData.CorruptDependency -f $Name)
}
}
$startupType = ConvertTo-StartupTypeString -StartMode $serviceCimInstance.StartMode
$builtInAccount = switch ($serviceCimInstance.StartName)
{
'NT Authority\NetworkService' { 'NetworkService'; break }
'NT Authority\LocalService' { 'LocalService'; break }
default { $serviceCimInstance.StartName }
}
$serviceResource = @{
Name = $Name
Ensure = 'Present'
Path = $serviceCimInstance.PathName
StartupType = $startupType
BuiltInAccount = $builtInAccount
State = $service.Status.ToString()
DisplayName = $service.DisplayName
Description = $serviceCimInstance.Description
DesktopInteract = $serviceCimInstance.DesktopInteract
Dependencies = $dependencies
}
}
else
{
Write-Verbose -Message ($script:localizedData.ServiceDoesNotExist -f $Name)
$serviceResource = @{
Name = $Name
Ensure = 'Absent'
}
}
return $serviceResource
}
<#
.SYNOPSIS
Creates, modifies, or deletes the service with the given name.
.PARAMETER Name
The name of the service to create, modify, or delete.
This may be different from the service's display name.
To retrieve a list of all services with their names and current states, use the Get-Service
cmdlet.
.PARAMETER Ensure
Ensures that the service is present or absent. Defaults to Present.
.PARAMETER Path
The path to the executable the service should run.
Required when creating a service.
The user account specified by BuiltInAccount or Credential must have access to this path in
order to start the service.
.PARAMETER StartupType
Indicates the startup type for the service.
.PARAMETER BuiltInAccount
The built-in account the service should start under.
Cannot be specified at the same time as Credential or GroupManagedServiceAccount.
The user account specified by this property must have access to the service executable path
defined by Path in order to start the service.
.PARAMETER GroupManagedServiceAccount
The Group Managed Service Account the service should start under. The GMSA
must be provided in DOMAIN\gMSA$ format or UPN format [email protected].
Cannot be specified at the same time as BuilInAccount or Credential.
.PARAMETER DesktopInteract
Indicates whether or not the service should be able to communicate with a window on the
desktop.
Must be false for services not running as LocalSystem.
The default value is false.
.PARAMETER State
The state the service should be in.
The default value is Running.
To disregard the state that the service is in, specify this property as Ignore.
.PARAMETER DisplayName
The display name the service should have.
.PARAMETER Description
The description the service should have.
.PARAMETER Dependencies
An array of the names of the dependencies the service should have.
.PARAMETER StartupTimeout
The time to wait for the service to start in milliseconds.
The default value is 30000 (30 seconds).
.PARAMETER TerminateTimeout
The time to wait for the service to stop in milliseconds.
The default value is 30000 (30 seconds).
.PARAMETER Credential
The credential of the user account the service should start under.
Cannot be specified at the same time as BuiltInAccount.
The user specified by this credential will automatically be granted the Log on as a Service
right.
The user account specified by this property must have access to the service executable path
defined by Path in order to start the service.
.NOTES
SupportsShouldProcess is enabled because Invoke-CimMethod calls ShouldProcess.
Here are the paths through which Set-TargetResource calls Invoke-CimMethod:
Set-TargetResource --> Set-ServicePath --> Invoke-CimMethod
--> Set-ServiceProperty --> Set-ServiceDependency --> Invoke-CimMethod
--> Set-ServiceAccountProperty --> Invoke-CimMethod
--> Set-ServiceStartupType --> Invoke-CimMethod
#>
function Set-TargetResource
{
[CmdletBinding(SupportsShouldProcess = $true)]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$Name,
[Parameter()]
[ValidateSet('Present', 'Absent')]
[System.String]
$Ensure = 'Present',
[Parameter()]
[ValidateNotNullOrEmpty()]
[System.String]
$Path,
[Parameter()]
[ValidateSet('Automatic', 'Manual', 'Disabled')]
[System.String]
$StartupType,
[Parameter()]
[ValidateSet('LocalSystem', 'LocalService', 'NetworkService')]
[System.String]
$BuiltInAccount,
[Parameter()]
[System.String]
$GroupManagedServiceAccount,
[Parameter()]
[ValidateSet('Running', 'Stopped', 'Ignore')]
[System.String]
$State = 'Running',
[Parameter()]
[System.Boolean]
$DesktopInteract = $false,
[Parameter()]
[ValidateNotNullOrEmpty()]
[System.String]
$DisplayName,
[Parameter()]
[ValidateNotNullOrEmpty()]
[System.String]
$Description,
[Parameter()]
[System.String[]]
[AllowEmptyCollection()]
$Dependencies,
[Parameter()]
[System.UInt32]
$StartupTimeout = 30000,
[Parameter()]
[System.UInt32]
$TerminateTimeout = 30000,
[Parameter()]
[ValidateNotNull()]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential
)
if ($PSBoundParameters.ContainsKey('StartupType'))
{
Assert-NoStartupTypeStateConflict -ServiceName $Name -StartupType $StartupType -State $State
}
if (($PSBoundParameters.ContainsKey('BuiltInAccount') -and $PSBoundParameters.ContainsKey('Credential')) -or
($PSBoundParameters.ContainsKey('BuiltInAccount') -and $PSBoundParameters.ContainsKey('GroupManagedServiceAccount')) -or
($PSBoundParameters.ContainsKey('GroupManagedServiceAccount') -and $PSBoundParameters.ContainsKey('Credential'))
)
{
$errorMessage = $script:localizedData.CredentialParametersAreMutallyExclusive -f $Name
New-InvalidArgumentException -ArgumentName 'BuiltInAccount / Credential / GroupManagedServiceAccount' -Message $errorMessage
}
$service = Get-Service -Name $Name -ErrorAction 'SilentlyContinue'
if ($Ensure -eq 'Absent')
{
if ($null -eq $service)
{
Write-Verbose -Message $script:localizedData.ServiceAlreadyAbsent
}
else
{
Write-Verbose -Message ($script:localizedData.RemovingService -f $Name)
Stop-ServiceWithTimeout -ServiceName $Name -TerminateTimeout $TerminateTimeout
Remove-ServiceWithTimeout -Name $Name -TerminateTimeout $TerminateTimeout
}
}
else
{
$serviceRestartNeeded = $false
# Create new service or update the service path if needed
if ($null -eq $service)
{
if ($PSBoundParameters.ContainsKey('Path'))
{
Write-Verbose -Message ($script:localizedData.CreatingService -f $Name, $Path)
$null = New-Service -Name $Name -BinaryPathName $Path
}
else
{
$errorMessage = $script:localizedData.ServiceDoesNotExistPathMissingError -f $Name
New-InvalidArgumentException -ArgumentName 'Path' -Message $errorMessage
}
}
else
{
if ($PSBoundParameters.ContainsKey('Path'))
{
$serviceRestartNeeded = Set-ServicePath -ServiceName $Name -Path $Path
}
}
# Update the properties of the service if needed
$setServicePropertyParameters = @{}
$servicePropertyParameterNames = @( 'StartupType', 'BuiltInAccount', 'Credential', 'GroupManagedServiceAccount', 'DesktopInteract', 'DisplayName', 'Description', 'Dependencies' )
foreach ($servicePropertyParameterName in $servicePropertyParameterNames)
{
if ($PSBoundParameters.ContainsKey($servicePropertyParameterName))
{
$setServicePropertyParameters[$servicePropertyParameterName] = $PSBoundParameters[$servicePropertyParameterName]
}
}
if ($setServicePropertyParameters.Count -gt 0)
{
Write-Verbose -Message ($script:localizedData.EditingServiceProperties -f $Name)
Set-ServiceProperty -ServiceName $Name @setServicePropertyParameters
}
# Update service state if needed
if ($State -eq 'Stopped')
{
Stop-ServiceWithTimeout -ServiceName $Name -TerminateTimeout $TerminateTimeout
}
elseif ($State -eq 'Running')
{
if ($serviceRestartNeeded)
{
Write-Verbose -Message ($script:localizedData.RestartingService -f $Name)
Stop-ServiceWithTimeout -ServiceName $Name -TerminateTimeout $TerminateTimeout
}
Start-ServiceWithTimeout -ServiceName $Name -StartupTimeout $StartupTimeout
}
}
}
<#
.SYNOPSIS
Tests if the service with the given name has the specified property values.
.PARAMETER Name
The name of the service to test.
This may be different from the service's display name.
To retrieve a list of all services with their names and current states, use the Get-Service
cmdlet.
.PARAMETER Ensure
Ensures that the service is present or absent. Defaults to Present.
.PARAMETER Path
The path to the executable the service should be running.
.PARAMETER StartupType
Indicates the startup type for the service.
.PARAMETER BuiltInAccount
The built-in account the service should start under.
Cannot be specified at the same time as Credential or GroupManagedServiceAccount.
.PARAMETER GroupManagedServiceAccount
The Group Managed Service Account the service should start under. The GMSA
must be provided in DOMAIN\gMSA$ format or UPN format [email protected].
Cannot be specified at the same time as BuilInAccount or Credential.
.PARAMETER DesktopInteract
Indicates whether or not the service should be able to communicate with a window on the
desktop.
Should be false for services not running as LocalSystem.
The default value is false.
.PARAMETER State
The state the service should be in.
The default value is Running.
To disregard the state that the service is in, specify this property as Ignore.
.PARAMETER DisplayName
The display name the service should have.
.PARAMETER Description
The description the service should have.
.PARAMETER Dependencies
An array of the names of the dependencies the service should have.
.PARAMETER StartupTimeout
Not used in Test-TargetResource.
.PARAMETER TerminateTimeout
Not used in Test-TargetResource.
.PARAMETER Credential
The credential the service should be running under.
Cannot be specified at the same time as BuiltInAccount.
#>
function Test-TargetResource
{
[OutputType([System.Boolean])]
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$Name,
[Parameter()]
[ValidateSet('Present', 'Absent')]
[System.String]
$Ensure = 'Present',
[Parameter()]
[ValidateNotNullOrEmpty()]
[System.String]
$Path,
[Parameter()]
[ValidateSet('Automatic', 'Manual', 'Disabled')]
[System.String]
$StartupType,
[Parameter()]
[ValidateSet('LocalSystem', 'LocalService', 'NetworkService')]
[System.String]
$BuiltInAccount,
[Parameter()]
[System.String]
$GroupManagedServiceAccount,
[Parameter()]
[System.Boolean]
$DesktopInteract = $false,
[Parameter()]
[ValidateSet('Running', 'Stopped', 'Ignore')]
[System.String]
$State = 'Running',
[Parameter()]
[ValidateNotNull()]
[System.String]
$DisplayName,
[Parameter()]
[System.String]
[AllowEmptyString()]
$Description,
[Parameter()]
[System.String[]]
[AllowEmptyCollection()]
$Dependencies,
[Parameter()]
[System.UInt32]
$StartupTimeout = 30000,
[Parameter()]
[System.UInt32]
$TerminateTimeout = 30000,
[Parameter()]
[ValidateNotNull()]
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential
)
if ($PSBoundParameters.ContainsKey('StartupType'))
{
Assert-NoStartupTypeStateConflict -ServiceName $Name -StartupType $StartupType -State $State
}
if (($PSBoundParameters.ContainsKey('BuiltInAccount') -and $PSBoundParameters.ContainsKey('Credential')) -or
($PSBoundParameters.ContainsKey('BuiltInAccount') -and $PSBoundParameters.ContainsKey('GroupManagedServiceAccount')) -or
($PSBoundParameters.ContainsKey('GroupManagedServiceAccount') -and $PSBoundParameters.ContainsKey('Credential'))
)
{
$errorMessage = $script:localizedData.CredentialParametersAreMutallyExclusive -f $Name
New-InvalidArgumentException -ArgumentName 'BuiltInAccount / Credential / GroupManagedServiceAccount' -Message $errorMessage
}
$serviceResource = Get-TargetResource -Name $Name
if ($serviceResource.Ensure -eq 'Absent')
{
Write-Verbose -Message ($script:localizedData.ServiceDoesNotExist -f $Name)
if ($StartupType -eq 'Disabled')
{
return $true
}
return ($Ensure -eq 'Absent')
}
else
{
Write-Verbose -Message ($script:localizedData.ServiceExists -f $Name)
if ($Ensure -eq 'Absent')
{
return $false
}
# Check the service path
if ($PSBoundParameters.ContainsKey('Path'))
{
$pathsMatch = Test-PathsMatch -ExpectedPath $Path -ActualPath $serviceResource.Path
if (-not $pathsMatch)
{
Write-Verbose -Message ($script:localizedData.ServicePathDoesNotMatch -f $Name, $Path, $serviceResource.Path)
return $false
}
}
# Check the service display name
if ($PSBoundParameters.ContainsKey('DisplayName') -and $serviceResource.DisplayName -ine $DisplayName)
{
Write-Verbose -Message ($script:localizedData.ServicePropertyDoesNotMatch -f 'DisplayName', $Name, $DisplayName, $serviceResource.DisplayName)
return $false
}
# Check the service description
if ($PSBoundParameters.ContainsKey('Description') -and $serviceResource.Description -ine $Description)
{
Write-Verbose -Message ($script:localizedData.ServicePropertyDoesNotMatch -f 'Description', $Name, $Description, $serviceResource.Description)
return $false
}
# Check the service dependencies
if ($PSBoundParameters.ContainsKey('Dependencies'))
{
$serviceDependenciesDoNotMatch = $false
if ($null -eq $serviceResource.Dependencies -xor $null -eq $Dependencies)
{
$serviceDependenciesDoNotMatch = $true
}
elseif ($null -ne $serviceResource.Dependencies -and $null -ne $Dependencies)
{
$mismatchedDependencies = Compare-Object -ReferenceObject $serviceResource.Dependencies -DifferenceObject $Dependencies
$serviceDependenciesDoNotMatch = $null -ne $mismatchedDependencies
}
if ($serviceDependenciesDoNotMatch)
{
$expectedDependenciesString = $Dependencies -join ','
$actualDependenciesString = $serviceResource.Dependencies -join ','
Write-Verbose -Message ($script:localizedData.ServicePropertyDoesNotMatch -f 'Dependencies', $Name, $expectedDependenciesString, $actualDependenciesString)
return $false
}
}
# Check the service desktop interation setting
if ($PSBoundParameters.ContainsKey('DesktopInteract') -and $serviceResource.DesktopInteract -ine $DesktopInteract)
{
Write-Verbose -Message ($script:localizedData.ServicePropertyDoesNotMatch -f 'DesktopInteract', $Name, $DesktopInteract, $serviceResource.DesktopInteract)
return $false
}
# Check the service account properties
if ($PSBoundParameters.ContainsKey('BuiltInAccount') -and $serviceResource.BuiltInAccount -ine $BuiltInAccount)
{
Write-Verbose -Message ($script:localizedData.ServicePropertyDoesNotMatch -f 'BuiltInAccount', $Name, $BuiltInAccount, $serviceResource.BuiltInAccount)
return $false
}
elseif ($PSBoundParameters.ContainsKey('GroupManagedServiceAccount'))
{
$expectedStartName = ConvertTo-StartName -Username $GroupManagedServiceAccount
if ($serviceResource.BuiltInAccount -ine $expectedStartName)
{
Write-Verbose -Message ($script:localizedData.GroupManagedServiceCredentialDoesNotMatch -f $Name, $GroupManagedServiceAccount, $serviceResource.BuiltInAccount)
return $false
}
}
elseif ($PSBoundParameters.ContainsKey('Credential'))
{
$expectedStartName = ConvertTo-StartName -Username $Credential.UserName
if ($serviceResource.BuiltInAccount -ine $expectedStartName)
{
Write-Verbose -Message ($script:localizedData.ServiceCredentialDoesNotMatch -f $Name, $Credential.UserName, $serviceResource.BuiltInAccount)
return $false
}
}
# Check the service startup type
if ($PSBoundParameters.ContainsKey('StartupType') -and $serviceResource.StartupType -ine $StartupType)
{
Write-Verbose -Message ($script:localizedData.ServicePropertyDoesNotMatch -f 'StartupType', $Name, $StartupType, $serviceResource.StartupType)
return $false
}
# Check the service state
if ($State -ne 'Ignore' -and $serviceResource.State -ine $State)
{
Write-Verbose -Message ($script:localizedData.ServicePropertyDoesNotMatch -f 'State', $Name, $State, $serviceResource.State)
return $false
}
}
return $true
}
<#
.SYNOPSIS
Retrieves the CIM instance of the service with the given name.
.PARAMETER ServiceName
The name of the service to get the CIM instance of.
#>
function Get-ServiceCimInstance
{
[OutputType([Microsoft.Management.Infrastructure.CimInstance])]
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullorEmpty()]
$ServiceName
)
return Get-CimInstance -ClassName 'Win32_Service' -Filter "Name='$ServiceName'"
}
<#
.SYNOPSIS
Converts the StartMode value returned in a CIM instance of a service to the format
expected by this resource.
.PARAMETER StartMode
The StartMode value to convert.
#>
function ConvertTo-StartupTypeString
{
[OutputType([System.String])]
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateSet('Auto', 'Manual', 'Disabled')]
[System.String]
$StartMode
)
if ($StartMode -eq 'Auto')
{
return 'Automatic'
}
return $StartMode
}
<#
.SYNOPSIS
Throws an invalid argument error if the given service startup type conflicts with the given
service state.
.PARAMETER ServiceName
The name of the service for the error message.
.PARAMETER StartupType
The service startup type to check.
.PARAMETER State
The service state to check.
#>
function Assert-NoStartupTypeStateConflict
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$ServiceName,
[Parameter(Mandatory = $true)]
[ValidateSet('Automatic', 'Manual', 'Disabled')]
[System.String]
$StartupType,
[Parameter(Mandatory = $true)]
[ValidateSet('Running', 'Stopped', 'Ignore')]
[System.String]
$State
)
if ($State -eq 'Stopped')
{
if ($StartupType -eq 'Automatic')
{
# Cannot stop a service and set it to start automatically at the same time
$errorMessage = $script:localizedData.StartupTypeStateConflict -f $ServiceName, $StartupType, $State
New-InvalidArgumentException -ArgumentName 'StartupType and State' -Message $errorMessage
}
}
elseif ($State -eq 'Running')
{
if ($StartupType -eq 'Disabled')
{
# Cannot start a service and disable it at the same time
$errorMessage = $script:localizedData.StartupTypeStateConflict -f $ServiceName, $StartupType, $State
New-InvalidArgumentException -ArgumentName 'StartupType and State' -Message $errorMessage
}
}
}
<#
.SYNOPSIS
Tests if the two given paths match.
.PARAMETER ExpectedPath
The expected path to test against.
.PARAMETER ActualPath
The actual path to test.
#>
function Test-PathsMatch
{
[OutputType([System.Boolean])]
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$ExpectedPath,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$ActualPath
)
return (0 -eq [System.String]::Compare($ExpectedPath, $ActualPath, [System.Globalization.CultureInfo]::CurrentUICulture))
}
<#
.SYNOPSIS
Converts the given username to the string version of it that would be expected in a
service's StartName property.
.PARAMETER Username
The username to convert.
#>
function ConvertTo-StartName
{
[OutputType([System.String])]
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$Username
)
$startName = $Username
if ($Username -ieq 'NetworkService' -or $Username -ieq 'LocalService')
{
$startName = "NT Authority\$Username"
}
elseif (-not $Username.Contains('\') -and -not $Username.Contains('@'))
{
$startName = ".\$Username"
}
elseif ($Username.StartsWith("$env:computerName\"))
{
$startName = $Username.Replace($env:computerName, '.')
}
return $startName
}
<#
.SYNOPSIS
Sets the executable path of the service with the given name.
Returns a boolean specifying whether a restart is needed or not.
.PARAMETER ServiceName
The name of the service to set the path of.
.PARAMETER Path
The path to set for the service.
.NOTES
SupportsShouldProcess is enabled because Invoke-CimMethod calls ShouldProcess.
This function calls Invoke-CimMethod directly.
#>
function Set-ServicePath
{
[OutputType([System.Boolean])]
[CmdletBinding(SupportsShouldProcess = $true)]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$ServiceName,
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$Path
)
$serviceCimInstance = Get-ServiceCimInstance -ServiceName $ServiceName
$pathsMatch = Test-PathsMatch -ExpectedPath $Path -ActualPath $serviceCimInstance.PathName
if ($pathsMatch)
{
Write-Verbose -Message ($script:localizedData.ServicePathMatches -f $ServiceName)
return $false
}
else
{
Write-Verbose -Message ($script:localizedData.ServicePathDoesNotMatch -f $ServiceName)
$changeServiceArguments = @{
PathName = $Path
}
$changeServiceResult = Invoke-CimMethod `
-InputObject $serviceCimInstance `
-MethodName 'Change' `
-Arguments $changeServiceArguments
if ($changeServiceResult.ReturnValue -ne 0)
{
$serviceChangePropertyString = $changeServiceArguments.Keys -join ', '
$errorMessage = $script:localizedData.InvokeCimMethodFailed -f 'Change', $ServiceName, $serviceChangePropertyString, $changeServiceResult.ReturnValue
New-InvalidArgumentException -ArgumentName 'Path' -Message $errorMessage
}
return $true
}
}
<#
.SYNOPSIS
Sets the dependencies of the service with the given name.
.PARAMETER ServiceName
The name of the service to set the dependencies of.
.PARAMETER Dependencies
The names of the dependencies to set for the service.
.NOTES
SupportsShouldProcess is enabled because Invoke-CimMethod calls ShouldProcess.
This function calls Invoke-CimMethod directly.
#>
function Set-ServiceDependency
{
[CmdletBinding(SupportsShouldProcess = $true)]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$ServiceName,
[Parameter(Mandatory = $true)]
[System.String[]]
[AllowEmptyCollection()]
$Dependencies
)
$service = Get-Service -Name $ServiceName -ErrorAction 'SilentlyContinue'
$serviceDependenciesMatch = $true
$noActualServiceDependencies = $null -eq $service.ServicesDependedOn -or 0 -eq $service.ServicesDependedOn.Count
$noExpectedServiceDependencies = $null -eq $Dependencies -or 0 -eq $Dependencies.Count
if ($noActualServiceDependencies -xor $noExpectedServiceDependencies)
{
$serviceDependenciesMatch = $false
}
elseif (-not $noActualServiceDependencies -and -not $noExpectedServiceDependencies)
{
$mismatchedDependencies = Compare-Object -ReferenceObject $service.ServicesDependedOn.Name -DifferenceObject $Dependencies
$serviceDependenciesMatch = $null -eq $mismatchedDependencies
}
if ($serviceDependenciesMatch)
{
Write-Verbose -Message ($script:localizedData.ServiceDepdenciesMatch -f $ServiceName)
}
else
{
Write-Verbose -Message ($script:localizedData.ServiceDepdenciesDoNotMatch -f $ServiceName)
$serviceCimInstance = Get-ServiceCimInstance -ServiceName $ServiceName
$changeServiceArguments = @{
ServiceDependencies = $Dependencies
}
$changeServiceResult = Invoke-CimMethod `
-InputObject $serviceCimInstance `
-MethodName 'Change' `
-Arguments $changeServiceArguments
if ($changeServiceResult.ReturnValue -ne 0)
{
$serviceChangePropertyString = $changeServiceArguments.Keys -join ', '
$errorMessage = $script:localizedData.InvokeCimMethodFailed -f 'Change', $ServiceName, $serviceChangePropertyString, $changeServiceResult.ReturnValue
New-InvalidArgumentException -Message $errorMessage -ArgumentName 'Dependencies'
}
}
}
<#
.SYNOPSIS
Grants the 'Log on as a service' right to the user with the given username.
.PARAMETER Username
The username of the user to grant 'Log on as a service' right to
#>
function Grant-LogOnAsServiceRight
{
[CmdletBinding()]
param
(
[Parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.String]
$Username
)
$logOnAsServiceText = @"
namespace LogOnAsServiceHelper
{
using Microsoft.Win32.SafeHandles;
using System;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices;
using System.Security;
public class NativeMethods
{
#region constants
// from ntlsa.h
private const int POLICY_LOOKUP_NAMES = 0x00000800;
private const int POLICY_CREATE_ACCOUNT = 0x00000010;
private const uint ACCOUNT_ADJUST_SYSTEM_ACCESS = 0x00000008;
private const uint ACCOUNT_VIEW = 0x00000001;
private const uint SECURITY_ACCESS_SERVICE_LOGON = 0x00000010;
// from LsaUtils.h
private const uint STATUS_OBJECT_NAME_NOT_FOUND = 0xC0000034;
// from lmcons.h
private const int UNLEN = 256;
private const int DNLEN = 15;
// Extra characteres for '\', '@' etc.
private const int EXTRA_LENGTH = 3;
#endregion constants
#region interop structures
/// <summary>
/// Used to open a policy, but not containing anything meaqningful