DSCResources/MSFT_xServiceResource/MSFT_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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
<#
    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'

# Import CommonResourceHelper for Get-LocalizedData, Test-IsNanoServer, New-InvalidArgumentException, New-InvalidOperationException
$script:dscResourcesFolderFilePath = Split-Path $PSScriptRoot -Parent
$script:commonResourceHelperFilePath = Join-Path -Path $script:dscResourcesFolderFilePath -ChildPath 'CommonResourceHelper.psm1'
Import-Module -Name $script:commonResourceHelperFilePath

# Localized messages for verbose and error statements in this resource
$script:localizedData = Get-LocalizedData -ResourceName 'MSFT_xServiceResource'

<#
    .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.
#>

function Get-TargetResource
{
    [OutputType([Hashtable])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [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)
        {
            $dependencies += $serviceDependedOn.Name.ToString()
        }

        $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
        Specifies whether the service should exist or not.
         
        Set this property to Present to create or modify a service.
        Set this property to Absent to delete a service.
 
        The default value is 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
        The startup type the service should have.
 
    .PARAMETER BuiltInAccount
        The built-in account the service should start under.
 
        Cannot be specified at the same time as Credential.
 
        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 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-ServiceDependencies --> Invoke-CimMethod
                                                   --> Set-ServiceAccountProperty --> Invoke-CimMethod
                                                   --> Set-ServiceStartupType --> Invoke-CimMethod
#>

function Set-TargetResource
{
    [CmdletBinding(SupportsShouldProcess = $true)]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $Name,

        [ValidateSet('Present', 'Absent')]
        [String]
        $Ensure = 'Present',

        [ValidateNotNullOrEmpty()]
        [String]
        $Path,

        [ValidateSet('Automatic', 'Manual', 'Disabled')]
        [String]
        $StartupType,

        [ValidateSet('LocalSystem', 'LocalService', 'NetworkService')]
        [String]
        $BuiltInAccount,

        [ValidateSet('Running', 'Stopped', 'Ignore')]
        [String]
        $State = 'Running',

        [Boolean]
        $DesktopInteract = $false,

        [ValidateNotNullOrEmpty()]
        [String]
        $DisplayName,

        [ValidateNotNullOrEmpty()]
        [String]
        $Description,

        [String[]]
        [AllowEmptyCollection()]
        $Dependencies,

        [UInt32]
        $StartupTimeout = 30000,

        [UInt32]
        $TerminateTimeout = 30000,

        [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'))
    {
        $errorMessage = $script:localizedData.BuiltInAccountAndCredentialSpecified -f $Name
        New-InvalidArgumentException -ArgumentName 'BuiltInAccount & Credential' -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', '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
        Specifies whether the service should exist or not.
         
        Set this property to Present to test if a service exists.
        Set this property to Absent to test if a service does not exist.
 
        The default value is Present.
 
    .PARAMETER Path
        The path to the executable the service should be running.
 
    .PARAMETER StartupType
        The startup type the service should have.
 
    .PARAMETER BuiltInAccount
        The account the service should be starting under.
 
        Cannot be specified at the same time as 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([Boolean])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $Name,
      
        [ValidateSet('Present', 'Absent')]
        [String]
        $Ensure = 'Present',

        [ValidateNotNullOrEmpty()]
        [String]
        $Path,

        [ValidateSet('Automatic', 'Manual', 'Disabled')]
        [String]
        $StartupType,

        [ValidateSet('LocalSystem', 'LocalService', 'NetworkService')]
        [String]
        $BuiltInAccount,

        [Boolean]
        $DesktopInteract = $false,

        [ValidateSet('Running', 'Stopped', 'Ignore')]
        [String]
        $State = 'Running',

        [ValidateNotNull()]
        [String]
        $DisplayName,

        [String]
        [AllowEmptyString()]
        $Description,

        [String[]]
        [AllowEmptyCollection()]
        $Dependencies,

        [UInt32]
        $StartupTimeout = 30000,

        [UInt32]
        $TerminateTimeout = 30000,

        [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'))
    {
        $errorMessage = $script:localizedData.BuiltInAccountAndCredentialSpecified -f $Name
        New-InvalidArgumentException -ArgumentName 'BuiltInAccount & Credential' -Message $errorMessage
    }

    $serviceResource = Get-TargetResource -Name $Name

    if ($serviceResource.Ensure -eq 'Absent')
    {
        Write-Verbose -Message ($script:localizedData.ServiceDoesNotExist -f $Name)
        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('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([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([String])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateSet('Auto', 'Manual', 'Disabled')]
        [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()]
        [String]
        $ServiceName,

        [Parameter(Mandatory = $true)]
        [ValidateSet('Automatic', 'Manual', 'Disabled')]
        [String]
        $StartupType,

        [Parameter(Mandatory = $true)]
        [ValidateSet('Running', 'Stopped', 'Ignore')]
        [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([Boolean])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ExpectedPath,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ActualPath
    )

    return (0 -eq [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([String])]
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [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([Boolean])]
    [CmdletBinding(SupportsShouldProcess = $true)]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ServiceName,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [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-ServiceDependencies
{
    [CmdletBinding(SupportsShouldProcess = $true)]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ServiceName,

        [Parameter(Mandatory = $true)]
        [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()]
        [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
                /// </summary>
                [StructLayout(LayoutKind.Sequential)]
                private struct LSA_OBJECT_ATTRIBUTES
                {
                    public UInt32 Length;
                    public IntPtr RootDirectory;
                    public IntPtr ObjectName;
                    public UInt32 Attributes;
                    public IntPtr SecurityDescriptor;
                    public IntPtr SecurityQualityOfService;
 
                    public void Initialize()
                    {
                        this.Length = 0;
                        this.RootDirectory = IntPtr.Zero;
                        this.ObjectName = IntPtr.Zero;
                        this.Attributes = 0;
                        this.SecurityDescriptor = IntPtr.Zero;
                        this.SecurityQualityOfService = IntPtr.Zero;
                    }
                }
 
                /// <summary>
                /// LSA string
                /// </summary>
                [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
                private struct LSA_UNICODE_STRING
                {
                    internal ushort Length;
                    internal ushort MaximumLength;
                    [MarshalAs(UnmanagedType.LPWStr)]
                    internal string Buffer;
 
                    internal void Set(string src)
                    {
                        this.Buffer = src;
                        this.Length = (ushort)(src.Length * sizeof(char));
                        this.MaximumLength = (ushort)(this.Length + sizeof(char));
                    }
                }
 
                /// <summary>
                /// Structure used as the last parameter for LSALookupNames
                /// </summary>
                [StructLayout(LayoutKind.Sequential)]
                private struct LSA_TRANSLATED_SID2
                {
                    public uint Use;
                    public IntPtr SID;
                    public int DomainIndex;
                    public uint Flags;
                };
                #endregion interop structures
 
                #region safe handles
                /// <summary>
                /// Handle for LSA objects including Policy and Account
                /// </summary>
                private class LsaSafeHandle : SafeHandleZeroOrMinusOneIsInvalid
                {
                    [DllImport("advapi32.dll")]
                    private static extern uint LsaClose(IntPtr ObjectHandle);
 
                    /// <summary>
                    /// Prevents a default instance of the LsaPolicySafeHAndle class from being created.
                    /// </summary>
                    private LsaSafeHandle(): base(true)
                    {
                    }
 
                    /// <summary>
                    /// Calls NativeMethods.CloseHandle(handle)
                    /// </summary>
                    /// <returns>the return of NativeMethods.CloseHandle(handle)</returns>
                    [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
                    protected override bool ReleaseHandle()
                    {
                        long returnValue = LsaSafeHandle.LsaClose(this.handle);
                        return returnValue != 0;
 
                    }
                }
 
                /// <summary>
                /// Handle for IntPtrs returned from Lsa calls that have to be freed with
                /// LsaFreeMemory
                /// </summary>
                private class SafeLsaMemoryHandle : SafeHandleZeroOrMinusOneIsInvalid
                {
                    [DllImport("advapi32")]
                    internal static extern int LsaFreeMemory(IntPtr Buffer);
 
                    private SafeLsaMemoryHandle() : base(true) { }
 
                    private SafeLsaMemoryHandle(IntPtr handle)
                        : base(true)
                    {
                        SetHandle(handle);
                    }
 
                    private static SafeLsaMemoryHandle InvalidHandle
                    {
                        get { return new SafeLsaMemoryHandle(IntPtr.Zero); }
                    }
 
                    override protected bool ReleaseHandle()
                    {
                        return SafeLsaMemoryHandle.LsaFreeMemory(handle) == 0;
                    }
 
                    internal IntPtr Memory
                    {
                        get
                        {
                            return this.handle;
                        }
                    }
                }
                #endregion safe handles
 
                #region interop function declarations
                /// <summary>
                /// Opens LSA Policy
                /// </summary>
                [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
                private static extern uint LsaOpenPolicy(
                    IntPtr SystemName,
                    ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
                    uint DesiredAccess,
                    out LsaSafeHandle PolicyHandle
                );
 
                /// <summary>
                /// Convert the name into a SID which is used in remaining calls
                /// </summary>
                [DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true), SuppressUnmanagedCodeSecurityAttribute]
                private static extern uint LsaLookupNames2(
                    LsaSafeHandle PolicyHandle,
                    uint Flags,
                    uint Count,
                    LSA_UNICODE_STRING[] Names,
                    out SafeLsaMemoryHandle ReferencedDomains,
                    out SafeLsaMemoryHandle Sids
                );
 
                /// <summary>
                /// Opens the LSA account corresponding to the user's SID
                /// </summary>
                [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
                private static extern uint LsaOpenAccount(
                    LsaSafeHandle PolicyHandle,
                    IntPtr Sid,
                    uint Access,
                    out LsaSafeHandle AccountHandle);
 
                /// <summary>
                /// Creates an LSA account corresponding to the user's SID
                /// </summary>
                [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
                private static extern uint LsaCreateAccount(
                    LsaSafeHandle PolicyHandle,
                    IntPtr Sid,
                    uint Access,
                    out LsaSafeHandle AccountHandle);
 
                /// <summary>
                /// Gets the LSA Account access
                /// </summary>
                [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
                private static extern uint LsaGetSystemAccessAccount(
                    LsaSafeHandle AccountHandle,
                    out uint SystemAccess);
 
                /// <summary>
                /// Sets the LSA Account access
                /// </summary>
                [DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
                private static extern uint LsaSetSystemAccessAccount(
                    LsaSafeHandle AccountHandle,
                    uint SystemAccess);
                #endregion interop function declarations
 
                /// <summary>
                /// Sets the Log On As A Service Policy for <paramref name="userName"/>, if not already set.
                /// </summary>
                /// <param name="userName">the user name we want to allow logging on as a service</param>
                /// <exception cref="ArgumentNullException">If the <paramref name="userName"/> is null or empty.</exception>
                /// <exception cref="InvalidOperationException">In the following cases:
                /// Failure opening the LSA Policy.
                /// The <paramref name="userName"/> is too large.
                /// Failure looking up the user name.
                /// Failure opening LSA account (other than account not found).
                /// Failure creating LSA account.
                /// Failure getting LSA account policy access.
                /// Failure setting LSA account policy access.
                /// </exception>
                public static void SetLogOnAsServicePolicy(string userName)
                {
                    if (String.IsNullOrEmpty(userName))
                    {
                        throw new ArgumentNullException("userName");
                    }
 
                    LSA_OBJECT_ATTRIBUTES objectAttributes = new LSA_OBJECT_ATTRIBUTES();
                    objectAttributes.Initialize();
 
                    // All handles are delcared in advance so they can be closed on finally
                    LsaSafeHandle policyHandle = null;
                    SafeLsaMemoryHandle referencedDomains = null;
                    SafeLsaMemoryHandle sids = null;
                    LsaSafeHandle accountHandle = null;
 
                    try
                    {
                        uint status = LsaOpenPolicy(
                            IntPtr.Zero,
                            ref objectAttributes,
                            POLICY_LOOKUP_NAMES | POLICY_CREATE_ACCOUNT,
                            out policyHandle);
 
                        if (status != 0)
                        {
                            throw new InvalidOperationException("CannotOpenPolicyErrorMessage");
                        }
 
                        // Unicode strings have a maximum length of 32KB. We don't want to create
                        // LSA strings with more than that. User lengths are much smaller so this check
                        // ensures userName's length is useful
                        if (userName.Length > UNLEN + DNLEN + EXTRA_LENGTH)
                        {
                            throw new InvalidOperationException("UserNameTooLongErrorMessage");
                        }
 
                        LSA_UNICODE_STRING lsaUserName = new LSA_UNICODE_STRING();
                        lsaUserName.Set(userName);
 
                        LSA_UNICODE_STRING[] names = new LSA_UNICODE_STRING[1];
                        names[0].Set(userName);
 
                        status = LsaLookupNames2(
                            policyHandle,
                            0,
                            1,
                            new LSA_UNICODE_STRING[] { lsaUserName },
                            out referencedDomains,
                            out sids);
 
                        if (status != 0)
                        {
                            throw new InvalidOperationException("CannotLookupNamesErrorMessage");
                        }
 
                        LSA_TRANSLATED_SID2 sid = (LSA_TRANSLATED_SID2)Marshal.PtrToStructure(sids.Memory, typeof(LSA_TRANSLATED_SID2));
 
                        status = LsaOpenAccount(policyHandle,
                                            sid.SID,
                                            ACCOUNT_VIEW | ACCOUNT_ADJUST_SYSTEM_ACCESS,
                                            out accountHandle);
 
                        uint currentAccess = 0;
 
                        if (status == 0)
                        {
                            status = LsaGetSystemAccessAccount(accountHandle, out currentAccess);
 
                            if (status != 0)
                            {
                                throw new InvalidOperationException("CannotGetAccountAccessErrorMessage");
                            }
 
                        }
                        else if (status == STATUS_OBJECT_NAME_NOT_FOUND)
                        {
                            status = LsaCreateAccount(
                                policyHandle,
                                sid.SID,
                                ACCOUNT_ADJUST_SYSTEM_ACCESS,
                                out accountHandle);
 
                            if (status != 0)
                            {
                                throw new InvalidOperationException("CannotCreateAccountAccessErrorMessage");
                            }
                        }
                        else
                        {
                            throw new InvalidOperationException("CannotOpenAccountErrorMessage");
                        }
 
                        if ((currentAccess & SECURITY_ACCESS_SERVICE_LOGON) == 0)
                        {
                            status = LsaSetSystemAccessAccount(
                                accountHandle,
                                currentAccess | SECURITY_ACCESS_SERVICE_LOGON);
                            if (status != 0)
                            {
                                throw new InvalidOperationException("CannotSetAccountAccessErrorMessage");
                            }
                        }
                    }
                    finally
                    {
                        if (policyHandle != null) { policyHandle.Close(); }
                        if (referencedDomains != null) { referencedDomains.Close(); }
                        if (sids != null) { sids.Close(); }
                        if (accountHandle != null) { accountHandle.Close(); }
                    }
                }
            }
        }
"@


    try
    {
        $null = [LogOnAsServiceHelper.NativeMethods]
    }
    catch
    {
        $logOnAsServiceText = $logOnAsServiceText.Replace('CannotOpenPolicyErrorMessage', `
            $script:localizedData.CannotOpenPolicyErrorMessage)
        $logOnAsServiceText = $logOnAsServiceText.Replace('UserNameTooLongErrorMessage', `
            $script:localizedData.UserNameTooLongErrorMessage)
        $logOnAsServiceText = $logOnAsServiceText.Replace('CannotLookupNamesErrorMessage', `
            $script:localizedData.CannotLookupNamesErrorMessage)
        $logOnAsServiceText = $logOnAsServiceText.Replace('CannotOpenAccountErrorMessage', `
            $script:localizedData.CannotOpenAccountErrorMessage)
        $logOnAsServiceText = $logOnAsServiceText.Replace('CannotCreateAccountAccessErrorMessage', `
            $script:localizedData.CannotCreateAccountAccessErrorMessage)
        $logOnAsServiceText = $logOnAsServiceText.Replace('CannotGetAccountAccessErrorMessage', `
            $script:localizedData.CannotGetAccountAccessErrorMessage)
        $logOnAsServiceText = $logOnAsServiceText.Replace('CannotSetAccountAccessErrorMessage', `
            $script:localizedData.CannotSetAccountAccessErrorMessage)
        $null = Add-Type $logOnAsServiceText -PassThru
    }

    if ($Username.StartsWith('.\'))
    {
        $Username = $Username.Substring(2)
    }

    try
    {
        [LogOnAsServiceHelper.NativeMethods]::SetLogOnAsServicePolicy($Username)
    }
    catch
    {
        $errorMessage = $script:localizedData.ErrorSettingLogOnAsServiceRightsForUser -f $Username, $_.Exception.Message
        New-InvalidOperationException -Message $errorMessage
    }
}

<#
    .SYNOPSIS
        Sets the service properties involving the account the service is running under.
        (StartName, StartPassword, DesktopInteract)
 
    .PARAMETER ServiceName
        The name of the service to change the start name of.
 
    .PARAMETER BuiltInAccount
        The name of the built-in account to run the service under.
        This value will overwrite the Credential value if Credential is also declared.
 
    .PARAMETER Credential
        The user credential to run the service under.
        BuiltInAccount will overwrite this value if BuiltInAccount is also declared.
 
    .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.
 
    .NOTES
        DesktopInteract is included here because it can only be enabled when the service startup
        account name is LocalSystem. In order not to run into a conflict where one property has
        been updated before the other, both are updated here at the same time.
 
        SupportsShouldProcess is enabled because Invoke-CimMethod calls ShouldProcess.
        This function calls Invoke-CimMethod directly.
#>

function Set-ServiceAccountProperty
{
    [CmdletBinding(SupportsShouldProcess = $true)]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ServiceName,

        [Parameter()]
        [String]
        [ValidateSet('LocalSystem', 'LocalService', 'NetworkService')]
        $BuiltInAccount,

        [Parameter()]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]
        $Credential,

        [Parameter()]
        [Boolean]
        $DesktopInteract
    )

    $serviceCimInstance = Get-ServiceCimInstance -ServiceName $ServiceName

    $changeServiceArguments = @{}

    if ($PSBoundParameters.ContainsKey('BuiltInAccount'))
    {
        $startName = ConvertTo-StartName -Username $BuiltInAccount

        if ($serviceCimInstance.StartName -ine $startName)
        {
            $changeServiceArguments['StartName'] = $startName
            $changeServiceArguments['StartPassword'] = ''
        }
    }
    elseif ($PSBoundParameters.ContainsKey('Credential'))
    {
        $startName = ConvertTo-StartName -Username $Credential.UserName

        if ($serviceCimInstance.StartName -ine $startName)
        {
            Grant-LogOnAsServiceRight -Username $startName

            $changeServiceArguments['StartName'] = $startName
            $changeServiceArguments['StartPassword'] = $Credential.GetNetworkCredential().Password
        }
    }

    if ($PSBoundParameters.ContainsKey('DesktopInteract'))
    {
        if ($serviceCimInstance.DesktopInteract -ne $DesktopInteract)
        {
            $changeServiceArguments['DesktopInteract'] = $DesktopInteract
        }
    }

    if ($changeServiceArguments.Count -gt 0)
    {
        $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 'BuiltInAccount, Credential, or DesktopInteract' -Message $errorMessage
        }
    }
}

<#
    .SYNOPSIS
        Sets the startup type of the service with the given name.
 
    .PARAMETER ServiceName
        The name of the service to set the startup type of.
 
    .PARAMETER StartupType
        The startup type value to set for the service.
 
    .NOTES
        SupportsShouldProcess is enabled because Invoke-CimMethod calls ShouldProcess.
        This function calls Invoke-CimMethod directly.
#>

function Set-ServiceStartupType
{
    [CmdletBinding(SupportsShouldProcess = $true)]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ServiceName,

        [Parameter(Mandatory = $true)]
        [ValidateSet('Automatic', 'Manual', 'Disabled')]
        [String]
        $StartupType
    )

    $serviceCimInstance = Get-ServiceCimInstance -ServiceName $ServiceName
    $serviceStartupType = ConvertTo-StartupTypeString -StartMode $serviceCimInstance.StartMode

    if ($serviceStartupType -ieq $StartupType)
    {
        Write-Verbose -Message ($script:localizedData.ServiceStartupTypeMatches -f $ServiceName)
    }
    else
    {
        Write-Verbose -Message ($script:localizedData.ServiceStartupTypeDoesNotMatch -f $ServiceName)

        $changeServiceArguments = @{
            StartMode = $StartupType
        }

        $changeResult = Invoke-CimMethod `
            -InputObject $serviceCimInstance `
            -MethodName 'Change' `
            -Arguments $changeServiceArguments

        if ($changeResult.ReturnValue -ne 0)
        {
            $serviceChangePropertyString = $changeServiceArguments.Keys -join ', '
            $errorMessage = $script:localizedData.InvokeCimMethodFailed -f 'Change', $ServiceName, $serviceChangePropertyString, $changeResult.ReturnValue
            New-InvalidArgumentException -ArgumentName 'StartupType' -Message $errorMessage
        }
    }
}

<#
    .SYNOPSIS
        Sets the service with the given name to have the specified properties.
 
    .PARAMETER Name
        The name of the service to set the properties of.
 
    .PARAMETER DisplayName
        The display name the service should have.
 
    .PARAMETER Description
        The description the service should have.
 
    .PARAMETER Dependencies
        The names of the dependencies the service should have.
 
    .PARAMETER BuiltInAccount
        The built-in account the service should start under.
 
        Cannot be specified at the same time as Credential.
 
    .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.
 
    .PARAMETER DesktopInteract
        Indicates whether or not the service should be able to communicate with a window on the desktop.
 
    .PARAMETER StartupType
        The startup type the service should have.
 
    .NOTES
        SupportsShouldProcess is enabled because Invoke-CimMethod calls ShouldProcess.
        Here are the paths through which Set-ServiceProperty calls Invoke-CimMethod:
 
        Set-ServiceProperty --> Set-ServiceDependencies --> Invoke-CimMethod
                            --> Set-ServieceAccountProperty --> Invoke-CimMethod
                            --> Set-ServiceStartupType --> Invoke-CimMethod
#>

function Set-ServiceProperty
{
    [CmdletBinding(SupportsShouldProcess = $true)]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ServiceName,

        [Parameter()]
        [ValidateSet('Automatic', 'Manual', 'Disabled')]
        [String]
        $StartupType,

        [Parameter()]
        [ValidateSet('LocalSystem', 'LocalService', 'NetworkService')]
        [String]
        $BuiltInAccount,

        [Parameter()]
        [Boolean]
        $DesktopInteract,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [String]
        $DisplayName,

        [Parameter()]
        [ValidateNotNullOrEmpty()]
        [String]
        $Description,

        [Parameter()]
        [String[]]
        [AllowEmptyCollection()]
        $Dependencies,

        [Parameter()]
        [ValidateNotNull()]
        [System.Management.Automation.PSCredential]
        [System.Management.Automation.Credential()]
        $Credential
    )

    # Update display name and/or description if needed
    $serviceCimInstance = Get-ServiceCimInstance -ServiceName $ServiceName
    
    $setServiceParameters = @{}

    if ($PSBoundParameters.ContainsKey('DisplayName') -and $serviceCimInstance.DisplayName -ine $DisplayName)
    {
        $setServiceParameters['DisplayName'] = $DisplayName
    }

    if ($PSBoundParameters.ContainsKey('Description')  -and $serviceCimInstance.Description -ine $Description)
    {
        $setServiceParameters['Description'] = $Description
    }

    if ($setServiceParameters.Count -gt 0)
    {
        $null = Set-Service -Name $ServiceName @setServiceParameters
    }

    # Update service dependencies if needed
    if ($PSBoundParameters.ContainsKey('Dependencies'))
    {
        Set-ServiceDependencies -ServiceName $ServiceName -Dependencies $Dependencies
    }

    # Update service account properties if needed
    $setServiceAccountPropertyParameters = @{}

    if ($PSBoundParameters.ContainsKey('BuiltInAccount'))
    {
        $setServiceAccountPropertyParameters['BuiltInAccount'] = $BuiltInAccount
    }
    elseif ($PSBoundParameters.ContainsKey('Credential'))
    {
        $setServiceAccountPropertyParameters['Credential'] = $Credential
    }

    if ($PSBoundParameters.ContainsKey('DesktopInteract'))
    {
        $setServiceAccountPropertyParameters['DesktopInteract'] = $DesktopInteract
    }

    if ($setServiceAccountPropertyParameters.Count -gt 0)
    {
        Set-ServiceAccountProperty -ServiceName $ServiceName @setServiceAccountPropertyParameters
    }

    # Update startup type
    if ($PSBoundParameters.ContainsKey('StartupType'))
    {
        Set-ServiceStartupType -ServiceName $ServiceName -StartupType $StartupType
    }
}

<#
    .SYNOPSIS
        Deletes the service with the given name.
 
        This is a wrapper function for unit testing.
 
    .PARAMETER Name
        The name of the service to delete.
#>

function Remove-Service
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $Name
    )

    & 'sc.exe' 'delete' $Name
}

<#
    .SYNOPSIS
        Deletes the service with the given name and waits for the service to be deleted.
 
    .PARAMETER Name
        The name of the service to delete.
 
    .PARAMETER TerminateTimeout
        The time to wait for the service to be deleted in milliseconds.
#>

function Remove-ServiceWithTimeout
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $Name,

        [Parameter(Mandatory = $true)]
        [UInt32]
        $TerminateTimeout
    )

    Remove-Service -Name $Name

    $serviceDeleted = $false
    $start = [DateTime]::Now

    while (-not $serviceDeleted -and ([DateTime]::Now - $start).TotalMilliseconds -lt $TerminateTimeout)
    {
        $service = Get-Service -Name $Name -ErrorAction 'SilentlyContinue'

        if ($null -eq $service)
        {
            $serviceDeleted = $true
        }
        else
        {
            Write-Verbose -Message ($script:localizedData.WaitingForServiceDeletion -f $Name)
            Start-Sleep -Seconds 1
        }
    }

    if ($serviceDeleted)
    {
        Write-Verbose -Message ($script:localizedData.ServiceDeletionSucceeded -f $Name)
    }
    else
    {
        New-InvalidOperationException -Message ($script:localizedData.ServiceDeletionFailed -f $Name)
    }
}

<#
    .SYNOPSIS
        Waits for the service with the given name to reach the given state within the given time
        span.
         
        This is a wrapper function for unit testing.
 
    .PARAMETER ServiceName
        The name of the service that should be in the given state.
 
    .PARAMETER State
        The state the service should be in.
 
    .PARAMETER WaitTimeSpan
        A time span of how long to wait for the service to reach the desired state.
#>

function Wait-ServiceStateWithTimeout
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ServiceName,

        [Parameter(Mandatory = $true)]
        [System.ServiceProcess.ServiceControllerStatus]
        $State,

        [Parameter(Mandatory = $true)]
        [TimeSpan]
        $WaitTimeSpan
    )

    $service = Get-Service -Name $ServiceName -ErrorAction 'SilentlyContinue'
    $Service.WaitForStatus($State, $WaitTimeSpan)
}

<#
    .SYNOPSIS
        Starts the service with the given name, if it is not already running, and waits for the
        service to be running.
 
    .PARAMETER ServiceName
        The name of the service to start.
 
    .PARAMETER StartupTimeout
        The time to wait for the service to be running in milliseconds.
#>

function Start-ServiceWithTimeout
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ServiceName,

        [Parameter(Mandatory = $true)]
        [UInt32]
        $StartupTimeout
    )

    Start-Service -Name $ServiceName
    $waitTimeSpan = New-Object -TypeName 'TimeSpan' -ArgumentList (0, 0, 0, 0, $StartupTimeout)
    Wait-ServiceStateWithTimeout -ServiceName $ServiceName -State 'Running' -WaitTimeSpan $waitTimeSpan
}

<#
    .SYNOPSIS
        Stops the service with the given name, if it is not already stopped, and waits for the
        service to be stopped.
 
    .PARAMETER ServiceName
        The name of the service to stop.
 
    .PARAMETER TerminateTimeout
        The time to wait for the service to be stopped in milliseconds.
#>

function Stop-ServiceWithTimeout
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $ServiceName,

        [Parameter(Mandatory = $true)]
        [UInt32]
        $TerminateTimeout
    )

    Stop-Service -Name $ServiceName
    $waitTimeSpan = New-Object -TypeName 'TimeSpan' -ArgumentList (0, 0, 0, 0, $TerminateTimeout)
    Wait-ServiceStateWithTimeout -ServiceName $ServiceName -State 'Stopped' -WaitTimeSpan $waitTimeSpan
}