SystemExtensions.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
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
function Suspend-Process 
{

    param
    (
        [Parameter(ValueFromPipeline=$true,Mandatory=$true)]
        [System.Diagnostics.Process]$InputObject
    )

    process 
    {
        #Open Process
        try
        {
            Write-Verbose "Open Process started"
            
            $pProc = [SystemUtilities.ProcessHelper]::OpenProcess("SuspendResume", $false, $InputObject.Id)
            if ($pProc -eq  [IntPtr]::Zero)
            {
                throw "Unable to open process(ID: $($InputObject.Id))"
            }

            Write-Verbose "Open Process completed"
        }
        catch
        {
            Write-Error "Open Process failed. Details: $_" -ErrorAction 'Stop'
        }

        #Suspend Process
        try
        {
            Write-Verbose "Suspend Process started"
            
            $result = [SystemUtilities.ProcessHelper]::SuspendProcess($pProc)
            if ($result -ne 0)
            {
                throw "Failed with ErrorCode: $result"
            }

            Write-Verbose "Suspend Process completed"
        }
        catch
        {
            Write-Error "Suspend Process failed. Details: $_" -ErrorAction 'Stop'
        }
        finally
        {
            $null = [SystemUtilities.ProcessHelper]::CloseHandle($pProc)
        }
    }

}

function Resume-Process 
{

    param
    (
        [Parameter(ValueFromPipeline=$true,Mandatory=$true)]
        [System.Diagnostics.Process]$InputObject
    )

    process 
    {
        #Open Process
        try
        {
            Write-Verbose "Open Process started"
            
            $pProc = [SystemUtilities.ProcessHelper]::OpenProcess("SuspendResume", $false, $InputObject.Id)
            if ($pProc -eq  [IntPtr]::Zero)
            {
                throw "Unable to open process(ID: $($InputObject.Id))"
            }

            Write-Verbose "Open Process completed"
        }
        catch
        {
            Write-Error "Open Process failed. Details: $_" -ErrorAction 'Stop'
        }

        #Resume Process
        try
        {
            Write-Verbose "Resume Process started"
            
            $result = [SystemUtilities.ProcessHelper]::ResumeProcess($pProc)
            if ($result -ne 0)
            {
                throw "Failed with ErrorCode: $result"
            }

            Write-Verbose "Resume Process completed"
        }
        catch
        {
            Write-Error "Resume Process failed. Details: $_" -ErrorAction 'Stop'
        }
        finally
        {
            $null = [SystemUtilities.ProcessHelper]::CloseHandle($pProc)
        }
    }

}

function Suspend-Thread 
{

    param
    (
        [Parameter(ValueFromPipeline=$true,Mandatory=$true)]
        [System.Diagnostics.ProcessThread]$InputObject
    )

    process 
    {
        #Open Thread
        try
        {
            Write-Verbose "Open Thread started"
            
            $pThread = [SystemUtilities.ProcessHelper]::OpenThread("SuspendResume", $false, $InputObject.Id)
            if ($pThread -eq  [IntPtr]::Zero)
            {
                throw "Unable to open Thread(ID: $($InputObject.Id))"
            }

            Write-Verbose "Open Thread completed"
        }
        catch
        {
            Write-Error "Open Thread failed. Details: $_" -ErrorAction 'Stop'
        }

        #Suspend Thread
        try
        {
            Write-Verbose "Suspend Thread started"
            
            $result = [SystemUtilities.ProcessHelper]::SuspendThread($pThread)
            if ($result -ne 0)
            {
                throw "Failed with ErrorCode: $result"
            }

            Write-Verbose "Suspend Thread completed"
        }
        catch
        {
            Write-Error "Suspend Thread failed. Details: $_" -ErrorAction 'Stop'
        }
        finally
        {
            $null = [SystemUtilities.ProcessHelper]::CloseHandle($pThread)
        }
    }

}

function Resume-Thread 
{

    param
    (
        [Parameter(ValueFromPipeline=$true,Mandatory=$true)]
        [System.Diagnostics.ProcessThread]$InputObject
    )

    process 
    {
        #Open Thread
        try
        {
            Write-Verbose "Open Thread started"
            
            $pThread = [SystemUtilities.ProcessHelper]::OpenThread("SuspendResume", $false, $InputObject.Id)
            if ($pThread -eq  [IntPtr]::Zero)
            {
                throw "Unable to open Thread(ID: $($InputObject.Id))"
            }

            Write-Verbose "Open Thread completed"
        }
        catch
        {
            Write-Error "Open Thread failed. Details: $_" -ErrorAction 'Stop'
        }

        #Resume Thread
        try
        {
            Write-Verbose "Resume Thread started"
            
            $result = [SystemUtilities.ProcessHelper]::ResumeThread($pThread)
            if ($result -ne 0)
            {
                throw "Failed with ErrorCode: $result"
            }

            Write-Verbose "Resume Thread completed"
        }
        catch
        {
            Write-Error "Resume Thread failed. Details: $_" -ErrorAction 'Stop'
        }
        finally
        {
            $null = [SystemUtilities.ProcessHelper]::CloseHandle($pThread)
        }
    }

}

function Start-NewProcess
{
    [CmdletBinding(DefaultParameterSetName='Default')]
    [OutputType([System.Diagnostics.Process], ParameterSetName="Default")]
    [OutputType([string], ParameterSetName="Wait")]
    param
    (
        #FilePath
        [Parameter(Mandatory=$true)]
        [string]$FilePath,

        #Arguments
        [Parameter(Mandatory=$false)]
        [string]$Arguments,

        #WorkingDirectory
        [Parameter(Mandatory=$false)]
        [string]$WorkingDirectory,

        #PassThru
        [Parameter(Mandatory=$false,ParameterSetName='Default')]
        [switch]$PassThru = $false,

        #WaitTimeout
        [Parameter(Mandatory=$false,ParameterSetName='Wait')]
        [int]$WaitTimeout = 60,

        #ReturnResult
        [Parameter(Mandatory=$false,ParameterSetName='Wait')]
        [switch]$ReturnResult = $false
    )

    Process
    {
        try
        {
            ### Start the process
            try
            {
                ## Initializing the new process StartInfo object
                Write-Verbose -Message "Initializing the new process StartInfo preferences"

                $ProcessStartInfo = New-Object -TypeName System.Diagnostics.ProcessStartInfo -ArgumentList $FilePath
                $ProcessStartInfo.RedirectStandardOutput = $true
                $ProcessStartInfo.RedirectStandardError = $true
                $ProcessStartInfo.UseShellExecute = $false
                $ProcessStartInfo.CreateNoWindow = $true
                if ($PSBoundParameters.ContainsKey('WorkingDirectory'))
                {
                    $ProcessStartInfo.WorkingDirectory = $WorkingDirectory
                }
                   if ($PSBoundParameters.ContainsKey('Arguments'))
                {
                    $ProcessStartInfo.Arguments = $Arguments
                }
     
                ## Start the process
                $Process = [System.Diagnostics.Process]::Start($ProcessStartInfo)

                Write-Verbose -Message "The Process was started successfully"
            }
            catch
            {
                # Rethrow with custom message
                throw "The process failed to start. Details: $_" 
            }

            switch ($PSCmdlet.ParameterSetName)
            {
                'Default' {
                    if ($PassThru.IsPresent)
                    {
                        # Write the Process object in the Output Stream
                        $Process
                    }
                }

                'Wait' {
                    ## Start a Timer to monitor the WaitTimeout
                    $Timer = [System.Diagnostics.Stopwatch]::StartNew()

                    ## Wait for the process to complete
                    Write-Verbose -Message "Waiting for the process to complete (max $WaitTimeout seconds)"
                    $WaitCompleted = $false
                    while (-not $WaitCompleted)
                    {
                        # Check the process state
                        if ($Process.HasExited)
                        {
                            $WaitCompleted = $true
                            $Timer.Stop()
                        }
                        else
                        {
                            # Check if a Timeout is reached
                            if ($Timer.Elapsed.TotalSeconds -gt $WaitTimeout)
                            {
                                $Timer.Stop()
                                throw "Timeout of $WaitTimeout reached."
                            }

                            Start-Sleep -Milliseconds 250
                        }
                    }

                    Write-Verbose -Message "The process completed successfully"


                    ## Check exitcode
                    if ($Process.exitcode -ne 0)
                    {
                        # Throw errorcode + errormessage
                        try
                        {
                            Write-Verbose -Message "Reading data from Output and Error streams"

                            $errorMsg = "The process failed with exitcode $($Process.ExitCode)."
                            $ProcessOutput_Error = $Process.StandardError.ReadToEnd()
                            $ProcessOutput_Standard = $Process.StandardOutput.ReadToEnd()
                            if ($ProcessOutput_Error)
                            {
                                $errorMsg += " Details: $ProcessOutput_Error"
                            }
                            elseif ($ProcessOutput_Standard)
                            {
                                $errorMsg += "Details: $ProcessOutput_Standard"
                            }
                        }
                        catch
                        {
                            $errorMsg += " Failed to read data from Output and Error streams. Details: $_"
                        }
                        finally
                        {
                            throw $errorMsg
                        }
                    }
                    elseif ($ReturnResult.IsPresent)
                    {
                        # Return output
                        $Process.StandardOutput.ReadToEnd()
                    }
                }

                default
                {
                    throw "Unknown ParameterSetName $($PSCmdlet.ParameterSetName)"
                }
            }
        }
        catch
        {
            Write-Error -Exception ($_.Exception) -Message "$_" -Category NotSpecified -ErrorId 0 -TargetObject $MyInvocation.MyCommand.Name
        }
        finally
        {
            # Dispose
            if($Process)
            {
                $Process.Dispose()
            }
        }
    }
}

function Get-ServiceConfig
{
    [CmdletBinding()]
    [OutputType('System.Service')]
    param 
    (
        #Name
        [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$True)]
        [string[]]$Name,
        
        #ComputerName
        [parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$True)]
        [Alias('CN','__Server','PSComputername')]
        [string[]]$Computername = $env:COMPUTERNAME,

        #ServiceType
        [parameter(Mandatory=$false)]
        [ValidateSet('Win32','Win32OwnProcess','Win32ShareProcess','FileSystemDriver','KernelDriver','All','Interactive')]
        [string]$ServiceType = 'Win32'
    )
    
    Begin {
        If ($PSBoundParameters.ContainsKey('Debug')) {
            $DebugPreference = 'Continue'
        }
        #region Reflection
        Try {
            [void][Service.Trigger]
        }
        Catch {
            Write-Verbose 'Building pinvoke via reflection'
            #region Module Builder
            $Domain = [AppDomain]::CurrentDomain
            $DynAssembly = New-Object System.Reflection.AssemblyName('ServiceTrigger')
            $AssemblyBuilder = $Domain.DefineDynamicAssembly($DynAssembly, [System.Reflection.Emit.AssemblyBuilderAccess]::Run) # Only run in memory
            $ModuleBuilder = $AssemblyBuilder.DefineDynamicModule('ServiceTrigger', $False)
            #endregion Module Builder

            #region Enums

            #region SC_ENUM_TYPE
            $EnumBuilder = $ModuleBuilder.DefineEnum('SC_ENUM_TYPE', 'Public', [uint32])
            [void]$EnumBuilder.DefineLiteral('SC_ENUM_PROCESS_INFO', [uint32] 0x00000000)
            [void]$EnumBuilder.CreateType()
            #endregion SC_ENUM_TYPE

            #region ERROR_CONTROL
            $EnumBuilder = $ModuleBuilder.DefineEnum('ERROR_CONTROL', 'Public', [uint32])
            [void]$EnumBuilder.DefineLiteral('Ignore', [uint32] 0x00000000)
            [void]$EnumBuilder.DefineLiteral('Normal', [uint32] 0x00000001)
            [void]$EnumBuilder.DefineLiteral('Severe', [uint32] 0x00000002)
            [void]$EnumBuilder.DefineLiteral('Critical', [uint32] 0x00000003)
            [void]$EnumBuilder.CreateType()
            #endregion ERROR_CONTROL

            #region SERVICE_START_TYPE
            $EnumBuilder = $ModuleBuilder.DefineEnum('SERVICE_START_TYPE', 'Public', [uint32])
            [void]$EnumBuilder.DefineLiteral('BootStart', [uint32] 0x00000000)
            [void]$EnumBuilder.DefineLiteral('SystemStart', [uint32] 0x00000001)
            [void]$EnumBuilder.DefineLiteral('Auto', [uint32] 0x00000002)
            [void]$EnumBuilder.DefineLiteral('Manual', [uint32] 0x00000003)
            [void]$EnumBuilder.DefineLiteral('Disabled', [uint32] 0x00000004)
            [void]$EnumBuilder.CreateType()
            #endregion SERVICE_START_TYPE

            #region SERVICE_CONTROL_CODE
            $EnumBuilder = $ModuleBuilder.DefineEnum('SERVICE_CONTROL_CODE', 'Public', [uint32])
            [void]$EnumBuilder.DefineLiteral('Unknown', [uint32] 0x00000000)
            [void]$EnumBuilder.DefineLiteral('AcceptStop', [uint32] 0x00000001)
            [void]$EnumBuilder.DefineLiteral('AcceptPauseContinue', [uint32] 0x00000002)
            [void]$EnumBuilder.DefineLiteral('AcceptShutdown', [uint32] 0x00000004)
            [void]$EnumBuilder.DefineLiteral('AcceptParamChange', [uint32] 0x00000008)
            [void]$EnumBuilder.DefineLiteral('AcceptNetBindingChange', [uint32] 0x00000010)
            [void]$EnumBuilder.DefineLiteral('AcceptHardwareProfileChange', [uint32] 0x00000020)
            [void]$EnumBuilder.DefineLiteral('AcceptPowerEvent', [uint32] 0x00000040)
            [void]$EnumBuilder.DefineLiteral('AcceptSessionChange', [uint32] 0x00000080)
            [void]$EnumBuilder.DefineLiteral('AcceptPreShutdown', [uint32] 0x00000100)
            [void]$EnumBuilder.DefineLiteral('AcceptTimeChange', [uint32] 0x00000200)
            [void]$EnumBuilder.DefineLiteral('AcceptTriggerEvent', [uint32] 0x00000400)
            [void]$EnumBuilder.DefineLiteral('AcceptUserModeReboot', [uint32] 0x00000800)
            $EnumBuilder.SetCustomAttribute(
                [FlagsAttribute].GetConstructor([Type]::EmptyTypes),
                @()
            )
            [void]$EnumBuilder.CreateType()
            #endregion SERVICE_CONTROL_CODE

            #region SERVICE_FLAGS
            $EnumBuilder = $ModuleBuilder.DefineEnum('SERVICE_FLAGS', 'Public', [uint32])
            [void]$EnumBuilder.DefineLiteral('NotProcessOrNotRunning', [uint32] 0x00000000)
            [void]$EnumBuilder.DefineLiteral('ServiceRunsInSystemProcess', [uint32] 0x00000001)
            $EnumBuilder.SetCustomAttribute(
                [FlagsAttribute].GetConstructor([Type]::EmptyTypes),
                @()
            )
            [void]$EnumBuilder.CreateType()
            #endregion SERVICE_FLAGS

            #region SERVICE_STATES
            $EnumBuilder = $ModuleBuilder.DefineEnum('SERVICE_STATES', 'Public', [uint32])
            [void]$EnumBuilder.DefineLiteral('SERVICE_ACTIVE', [uint32] 0x00000001)
            [void]$EnumBuilder.DefineLiteral('SERVICE_INACTIVE', [uint32] 0x00000002)
            [void]$EnumBuilder.DefineLiteral('SERVICE_ALL', [uint32] 0x00000003)
            $EnumBuilder.SetCustomAttribute(
                [FlagsAttribute].GetConstructor([Type]::EmptyTypes),
                @()
            )
            [void]$EnumBuilder.CreateType()
            #endregion SERVICE_STATES

            #region SERVICE_STATE
            $EnumBuilder = $ModuleBuilder.DefineEnum('SERVICE_STATE', 'Public', [uint32])
            [void]$EnumBuilder.DefineLiteral('Stopped', [uint32] 0x00000001)
            [void]$EnumBuilder.DefineLiteral('StartPending', [uint32] 0x00000002)
            [void]$EnumBuilder.DefineLiteral('StopPending', [uint32] 0x00000003)
            [void]$EnumBuilder.DefineLiteral('Running', [uint32] 0x00000004)
            [void]$EnumBuilder.DefineLiteral('ContinuePending', [uint32] 0x00000005)
            [void]$EnumBuilder.DefineLiteral('PausePending', [uint32] 0x00000006)
            [void]$EnumBuilder.DefineLiteral('Paused', [uint32] 0x00000007)
                        $EnumBuilder.SetCustomAttribute(
                [FlagsAttribute].GetConstructor([Type]::EmptyTypes),
                @()
            )
            [void]$EnumBuilder.CreateType()
            #endregion SERVICE_STATE

            #region SERVICE_TYPE
            $EnumBuilder = $ModuleBuilder.DefineEnum('SERVICE_TYPE', 'Public', [uint32])
            [void]$EnumBuilder.DefineLiteral('KernelDriver', [uint32] 0x00000001)
            [void]$EnumBuilder.DefineLiteral('FileSystemDriver', [uint32] 0x00000002)
            [void]$EnumBuilder.DefineLiteral('Driver', [uint32] 0x0000000B)
            [void]$EnumBuilder.DefineLiteral('Win32OwnProcess', [uint32] 0x00000010)
            [void]$EnumBuilder.DefineLiteral('Win32ShareProcess', [uint32] 0x00000020)
            [void]$EnumBuilder.DefineLiteral('Win32', [uint32] 0x00000030)
            [void]$EnumBuilder.DefineLiteral('Interactive', [uint32] 0x00000100)
            [void]$EnumBuilder.DefineLiteral('All', [uint32] 0x0000013B)
                        $EnumBuilder.SetCustomAttribute(
                [FlagsAttribute].GetConstructor([Type]::EmptyTypes),
                @()
            )
            [void]$EnumBuilder.CreateType()
            #endregion SERVICE_TYPE

            #region SERVICE_SID_TYPE
            $EnumBuilder = $ModuleBuilder.DefineEnum('SERVICE_SID_TYPE', 'Public', [uint32])
            [void]$EnumBuilder.DefineLiteral('None', [uint32] 0x00000000)
            [void]$EnumBuilder.DefineLiteral('Unrestricted', [uint32] 0x00000001)
            [void]$EnumBuilder.DefineLiteral('Restricted', [uint32] 0x00000003)            
            [void]$EnumBuilder.CreateType()
            #endregion SERVICE_SID_TYPE

            #region SCM_ACCESS
            $EnumBuilder = $ModuleBuilder.DefineEnum('SCM_ACCESS', 'Public', [uint32])
            [void]$EnumBuilder.DefineLiteral('STANDARD_RIGHTS_REQUIRED', [uint32] 0x000F0000)
            [void]$EnumBuilder.DefineLiteral('SC_MANAGER_CONNECT', [uint32] 0x00001)
            [void]$EnumBuilder.DefineLiteral('SC_MANAGER_CREATE_SERVICE', [uint32] 0x00002)
            [void]$EnumBuilder.DefineLiteral('SC_MANAGER_ENUMERATE_SERVICE', [uint32] 0x00004)
            [void]$EnumBuilder.DefineLiteral('SC_MANAGER_LOCK', [uint32] 0x00008)
            [void]$EnumBuilder.DefineLiteral('SC_MANAGER_QUERY_LOCK_STATUS', [uint32] 0x00010)
            [void]$EnumBuilder.DefineLiteral('SC_MANAGER_MODIFY_BOOT_CONFIG', [uint32] 0x00020)
            [void]$EnumBuilder.DefineLiteral('SC_MANAGER_ALL_ACCESS', [uint32] 0xf003f)
                        $EnumBuilder.SetCustomAttribute(
                [FlagsAttribute].GetConstructor([Type]::EmptyTypes),
                @()
            )
            [void]$EnumBuilder.CreateType()
            #endregion SCM_ACCESS

            #region SERVICE_ACCESS
            $EnumBuilder = $ModuleBuilder.DefineEnum('SERVICE_ACCESS', 'Public', [uint32])
            [void]$EnumBuilder.DefineLiteral('STANDARD_RIGHTS_REQUIRED', [uint32] 0x000F0000)
            [void]$EnumBuilder.DefineLiteral('SERVICE_QUERY_CONFIG', [uint32] 0x00001)
            [void]$EnumBuilder.DefineLiteral('SERVICE_CHANGE_CONFIG', [uint32] 0x00002)
            [void]$EnumBuilder.DefineLiteral('SERVICE_QUERY_STATUS', [uint32] 0x00004)
            [void]$EnumBuilder.DefineLiteral('SERVICE_ENUMERATE_DEPENDENTS', [uint32] 0x00008)
            [void]$EnumBuilder.DefineLiteral('SERVICE_START', [uint32] 0x00010)
            [void]$EnumBuilder.DefineLiteral('SERVICE_STOP', [uint32] 0x00020)
            [void]$EnumBuilder.DefineLiteral('SERVICE_PAUSE_CONTINUE', [uint32] 0x00040)
            [void]$EnumBuilder.DefineLiteral('SERVICE_INTERROGATE', [uint32] 0x00080)
            [void]$EnumBuilder.DefineLiteral('SERVICE_USER_DEFINED_CONTROL', [uint32] 0x00100)
            [void]$EnumBuilder.DefineLiteral('SERVICE_ALL_ACCESS', [uint32] 0xf01ff)
                        $EnumBuilder.SetCustomAttribute(
                [FlagsAttribute].GetConstructor([Type]::EmptyTypes),
                @()
            )
            [void]$EnumBuilder.CreateType()
            #endregion SERVICE_ACCESS

            #region SERVICE_INFO_LEVEL
            $EnumBuilder = $ModuleBuilder.DefineEnum('SERVICE_INFO_LEVEL', 'Public', [uint32])
            [void]$EnumBuilder.DefineLiteral('SERVICE_CONFIG_DELAYED_AUTO_START_INFO', [uint32] 0x00000003)
            [void]$EnumBuilder.DefineLiteral('SERVICE_CONFIG_DESCRIPTION', [uint32] 0x00000001)
            [void]$EnumBuilder.DefineLiteral('SERVICE_CONFIG_FAILURE_ACTIONS', [uint32] 0x00000002)
            [void]$EnumBuilder.DefineLiteral('SERVICE_CONFIG_FAILURE_ACTIONS_FLAG', [uint32] 0x00000004)
            [void]$EnumBuilder.DefineLiteral('SERVICE_CONFIG_PREFERRED_NODE', [uint32] 0x00000009)
            [void]$EnumBuilder.DefineLiteral('SERVICE_CONFIG_PRESHUTDOWN_INFO', [uint32] 0x00000007)
            [void]$EnumBuilder.DefineLiteral('SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO', [uint32] 0x00000006)
            [void]$EnumBuilder.DefineLiteral('SERVICE_CONFIG_SERVICE_SID_INFO', [uint32] 0x00000005)
            [void]$EnumBuilder.DefineLiteral('SERVICE_CONFIG_TRIGGER_INFO', [uint32] 0x00000008)
            [void]$EnumBuilder.DefineLiteral('SERVICE_CONFIG_LAUNCH_PROTECTED', [uint32] 0x0000000c)
                        $EnumBuilder.SetCustomAttribute(
                [FlagsAttribute].GetConstructor([Type]::EmptyTypes),
                @()
            )
            [void]$EnumBuilder.CreateType()
            #endregion SERVICE_INFO_LEVEL

            #region TRIGGER_DATA_TYPE
            $EnumBuilder = $ModuleBuilder.DefineEnum('TRIGGER_DATA_TYPE', 'Public', [uint32])
            [void]$EnumBuilder.DefineLiteral('BINARY', [uint32] 0x00000001)
            [void]$EnumBuilder.DefineLiteral('STRING', [uint32] 0x00000002)
            [void]$EnumBuilder.DefineLiteral('LEVEL', [uint32] 0x00000003)
            [void]$EnumBuilder.DefineLiteral('KEYWORD_ANY', [uint32] 0x00000004)
            [void]$EnumBuilder.DefineLiteral('KEYWORD_ALL', [uint32] 0x00000005)
                        $EnumBuilder.SetCustomAttribute(
                [FlagsAttribute].GetConstructor([Type]::EmptyTypes),
                @()
            )
            [void]$EnumBuilder.CreateType()
            #endregion TRIGGER_DATA_TYPE

            #region TRIGGER_TYPE
            $EnumBuilder = $ModuleBuilder.DefineEnum('TRIGGER_TYPE', 'Public', [uint32])
            [void]$EnumBuilder.DefineLiteral('DeviceInterfaceArrival', [uint32] 0x00000001)
            [void]$EnumBuilder.DefineLiteral('IPAddressAvailability', [uint32] 0x00000002)
            [void]$EnumBuilder.DefineLiteral('DomainJoin', [uint32] 0x00000003)
            [void]$EnumBuilder.DefineLiteral('FirewallPortEvent', [uint32] 0x00000004)
            [void]$EnumBuilder.DefineLiteral('GroupPolicy', [uint32] 0x00000005)
            [void]$EnumBuilder.DefineLiteral('NetworkEndpoint', [uint32] 0x00000006)
            [void]$EnumBuilder.DefineLiteral('Custom', [uint32] 0x00000014)
                        $EnumBuilder.SetCustomAttribute(
                [FlagsAttribute].GetConstructor([Type]::EmptyTypes),
                @()
            )
            [void]$EnumBuilder.CreateType()
            #endregion TRIGGER_TYPE

            #region TRIGGER_ACTION
            $EnumBuilder = $ModuleBuilder.DefineEnum('TRIGGER_ACTION', 'Public', [uint32])
            [void]$EnumBuilder.DefineLiteral('ServiceStart', [uint32] 0x00000001)
            [void]$EnumBuilder.DefineLiteral('ServiceStop', [uint32] 0x00000002)
            [void]$EnumBuilder.CreateType()
            #endregion TRIGGER_ACTION

            #region SC_ACTION_TYPE
            $EnumBuilder = $ModuleBuilder.DefineEnum('SC_ACTION_TYPE', 'Public', [uint32])
            [void]$EnumBuilder.DefineLiteral('None', [uint32] 0x00000000)
            [void]$EnumBuilder.DefineLiteral('Restart', [uint32] 0x00000001)
            [void]$EnumBuilder.DefineLiteral('Reboot', [uint32] 0x00000002)
            [void]$EnumBuilder.DefineLiteral('RunCommand', [uint32] 0x00000003)
                        $EnumBuilder.SetCustomAttribute(
                [FlagsAttribute].GetConstructor([Type]::EmptyTypes),
                @()
            )
            [void]$EnumBuilder.CreateType()
            #endregion SC_ACTION_TYPE

            #endregion Enums

            #region Struct

            #region SERVICE_STATUS_PROCESS
            $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
            $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('SERVICE_STATUS_PROCESS', $Attributes, [System.ValueType], 8, 0x0)
            [void]$STRUCT_TypeBuilder.DefineField('dwServiceType', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwCurrentState', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwControlsAccepted', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwWin32ExitCode', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwServiceSpecificExitCode', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwCheckPoint', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwWaitHint', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwProcessId', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwServiceFlags', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.CreateType()
            #endregion SERVICE_STATUS_PROCESS

            #region SERVICE_STATUS
            $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
            $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('SERVICE_STATUS', $Attributes, [System.ValueType], 8, 0x0)
            [void]$STRUCT_TypeBuilder.DefineField('dwServiceType', [SERVICE_TYPE], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwCurrentState', [SERVICE_STATE], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwControlsAccepted', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwWin32ExitCode', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwServiceSpecificExitCode', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwCheckPoint', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwWaitHint', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.CreateType()
            #endregion SERVICE_STATUS

            #region QUERY_SERVICE_CONFIG
            $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
            $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('QUERY_SERVICE_CONFIG', $Attributes, [System.ValueType], 8, 0x0)
            [void]$STRUCT_TypeBuilder.DefineField('dwServiceType', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwStartType', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwErrorControl', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('lpBinaryPathName', [string], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('lpLoadOrderGroup', [string], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwTagId', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('lpDependencies', [string], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('lpServiceStartName', [string], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('lpDisplayName', [string], @('Public'))
            [void]$STRUCT_TypeBuilder.CreateType()
            #endregion QUERY_SERVICE_CONFIG

            If ([intptr]::Size -eq 8) {
                #region ENUM_SERVICE_STATUS_PROCESS
                $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
                $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('ENUM_SERVICE_STATUS_PROCESS', $Attributes, [System.ValueType], 8, 0x0)
                [void]$STRUCT_TypeBuilder.DefineField('lpServiceName', [string], @('Public'))
                [void]$STRUCT_TypeBuilder.DefineField('lpDisplayName', [string], @('Public'))
                [void]$STRUCT_TypeBuilder.DefineField('ServiceStatusProcess', [SERVICE_STATUS_PROCESS], @('Public'))
                [void]$STRUCT_TypeBuilder.CreateType()
                #endregion ENUM_SERVICE_STATUS_PROCESS
            } 
            Else {
                #region ENUM_SERVICE_STATUS_PROCESS
                $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
                $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('ENUM_SERVICE_STATUS_PROCESS', $Attributes, [System.ValueType], 4, 0x0)
                [void]$STRUCT_TypeBuilder.DefineField('lpServiceName', [string], @('Public'))
                [void]$STRUCT_TypeBuilder.DefineField('lpDisplayName', [string], @('Public'))
                [void]$STRUCT_TypeBuilder.DefineField('ServiceStatusProcess', [SERVICE_STATUS_PROCESS], @('Public'))
                [void]$STRUCT_TypeBuilder.CreateType()
                #endregion ENUM_SERVICE_STATUS_PROCESS
            }

            If ([intptr]::Size -eq 8) {
                #region ENUM_SERVICE_STATUS
                $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
                $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('ENUM_SERVICE_STATUS', $Attributes, [System.ValueType], 8, 0x0)
                [void]$STRUCT_TypeBuilder.DefineField('lpServiceName', [string], @('Public'))
                [void]$STRUCT_TypeBuilder.DefineField('lpDisplayName', [string], @('Public'))
                [void]$STRUCT_TypeBuilder.DefineField('ServiceStatus', [SERVICE_STATUS], @('Public'))
                [void]$STRUCT_TypeBuilder.CreateType()
                #endregion ENUM_SERVICE_STATUS
            }
            Else {
                #region ENUM_SERVICE_STATUS
                $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
                $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('ENUM_SERVICE_STATUS', $Attributes, [System.ValueType], 4, 0x0)
                [void]$STRUCT_TypeBuilder.DefineField('lpServiceName', [string], @('Public'))
                [void]$STRUCT_TypeBuilder.DefineField('lpDisplayName', [string], @('Public'))
                [void]$STRUCT_TypeBuilder.DefineField('ServiceStatus', [SERVICE_STATUS], @('Public'))
                [void]$STRUCT_TypeBuilder.CreateType()
                #endregion ENUM_SERVICE_STATUS
            } 

            #region TRIGGER
            $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
            $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('TRIGGER', $Attributes, [System.ValueType], 8, 0x0)
            [void]$STRUCT_TypeBuilder.DefineField('TriggerType', [TRIGGER_TYPE], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('Action', [TRIGGER_ACTION], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('SubType', [string], @('Public'))
            [void]$STRUCT_TypeBuilder.CreateType()
            #endregion TRIGGER

            #region SERVICE_REQUIRED_PRIVILEGES_INFO
            $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
            $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('SERVICE_REQUIRED_PRIVILEGES_INFO', $Attributes, [System.ValueType], 8, 0x0)
            [void]$STRUCT_TypeBuilder.DefineField('pmszRequiredPrivileges', [intptr], @('Public'))
            [void]$STRUCT_TypeBuilder.CreateType()
            #endregion SERVICE_REQUIRED_PRIVILEGES_INFO

            #region SC_ACTION
            $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
            $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('SC_ACTION', $Attributes, [System.ValueType], 8, 0x0)
            [void]$STRUCT_TypeBuilder.DefineField('type', [SC_ACTION_TYPE], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('delay', [uint32], @('Public'))
            [void]$STRUCT_TypeBuilder.CreateType()
            #endregion SC_ACTION

            #region SERVICE_FAILURE_ACTIONS
            $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
            $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('SERVICE_FAILURE_ACTIONS', $Attributes, [System.ValueType], 8, 0x0)
            [void]$STRUCT_TypeBuilder.DefineField('dwResetPeriod', [uint32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('lpRebootMsg', [string], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('lpCommand', [string], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('cActions', [uint32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('lpsaActions', [intptr], @('Public'))
            [void]$STRUCT_TypeBuilder.CreateType()
            #endregion SERVICE_FAILURE_ACTIONS

            #region SERVICE_FAILURE_ACTIONS_FLAG
            $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
            $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('SERVICE_FAILURE_ACTIONS_FLAG', $Attributes, [System.ValueType], 8, 0x0)
            [void]$STRUCT_TypeBuilder.DefineField('fFailureActionsOnNonCrashFailures', [bool], @('Public'))
            [void]$STRUCT_TypeBuilder.CreateType()
            #endregion SERVICE_FAILURE_ACTIONS_FLAG

            #region FAILURE_ACTIONS
            $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
            $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('FAILURE_ACTIONS', $Attributes, [System.ValueType], 8, 0x0)
            [void]$STRUCT_TypeBuilder.DefineField('ResetPeriod', [uint32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('RebootMessage', [string], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('Command', [string], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('Actions', [SC_ACTION[]], @('Public'))
            [void]$STRUCT_TypeBuilder.CreateType()
            #endregion FAILURE_ACTIONS

            #region SERVICE_PREFERRED_NODE_INFO
            $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
            $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('SERVICE_PREFERRED_NODE_INFO', $Attributes, [System.ValueType], 8, 0x0)
            [void]$STRUCT_TypeBuilder.DefineField('usPreferredNode', [int16], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('fDelete', [bool], @('Public'))
            [void]$STRUCT_TypeBuilder.CreateType()
            #endregion SERVICE_PREFERRED_NODE_INFO

            #region SERVICE_PRESHUTDOWN_INFO
            $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
            $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('SERVICE_PRESHUTDOWN_INFO', $Attributes, [System.ValueType], 8, 0x0)
            [void]$STRUCT_TypeBuilder.DefineField('dwPreshutdownTimeout', [uint32], @('Public'))
            [void]$STRUCT_TypeBuilder.CreateType()
            #endregion SERVICE_PRESHUTDOWN_INFO

            #region SERVICE_SID_INFO
            $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
            $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('SERVICE_SID_INFO', $Attributes, [System.ValueType], 8, 0x0)
            [void]$STRUCT_TypeBuilder.DefineField('dwServiceSidType', [uint32], @('Public'))
            [void]$STRUCT_TypeBuilder.CreateType()
            #endregion SERVICE_SID_INFO

            #region SERVICE_DELAYED_AUTO_START_INFO
            $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
            $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('SERVICE_DELAYED_AUTO_START_INFO', $Attributes, [System.ValueType], 8, 0x0)
            [void]$STRUCT_TypeBuilder.DefineField('fDelayedAutostart', [bool], @('Public'))
            [void]$STRUCT_TypeBuilder.CreateType()
            #endregion SERVICE_DELAYED_AUTO_START_INFO

            #region SERVICE_DESCRIPTION
            $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
            $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('SERVICE_DESCRIPTION', $Attributes, [System.ValueType], 8, 0x0)
            $ctor = [System.Runtime.InteropServices.MarshalAsAttribute].GetConstructor(@([System.Runtime.InteropServices.UnmanagedType]))
            $CustomAttribute = [System.Runtime.InteropServices.UnmanagedType]::LPStr
            $CustomAttributeBuilder = New-Object System.Reflection.Emit.CustomAttributeBuilder -ArgumentList $ctor, $CustomAttribute 
            $Field = $STRUCT_TypeBuilder.DefineField('lpDescription', [string], @('Public'))
            $Field.SetCustomAttribute($CustomAttributeBuilder)
            [void]$STRUCT_TypeBuilder.CreateType()
            #endregion SERVICE_DESCRIPTION

            #region SERVICE_TRIGGER_SPECIFIC_DATA_ITEM
            $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
            $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('SERVICE_TRIGGER_SPECIFIC_DATA_ITEM', $Attributes, [System.ValueType], 8, 0x0)
            [void]$STRUCT_TypeBuilder.DefineField('dwDataType', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('cbData', [uint32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('pData', [intptr], @('Public'))
            [void]$STRUCT_TypeBuilder.CreateType()
            #endregion SERVICE_TRIGGER_SPECIFIC_DATA_ITEM

            #region SERVICE_TRIGGER
            $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
            $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('SERVICE_TRIGGER', $Attributes, [System.ValueType], 8, 0x0)
            [void]$STRUCT_TypeBuilder.DefineField('dwTriggerType', [TRIGGER_TYPE], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('dwAction', [TRIGGER_ACTION], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('pTriggerSubType', [IntPtr], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('cDataItems', [uint32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('pDataItems', [IntPtr], @('Public'))
            [void]$STRUCT_TypeBuilder.CreateType()
            #endregion SERVICE_TRIGGER

            #region SERVICE_TRIGGER_INFO
            $Attributes = 'AutoLayout, AnsiClass, Class, Public, SequentialLayout, Sealed, BeforeFieldInit'
            $STRUCT_TypeBuilder = $ModuleBuilder.DefineType('SERVICE_TRIGGER_INFO', $Attributes, [System.ValueType], 8, 0x0)
            [void]$STRUCT_TypeBuilder.DefineField('cTriggers', [int32], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('pTriggers', [Intptr], @('Public'))
            [void]$STRUCT_TypeBuilder.DefineField('pReserved', [intptr], @('Public'))
            [void]$STRUCT_TypeBuilder.CreateType()
            #endregion SERVICE_TRIGGER_INFO

            #endregion Struct

            $TypeBuilder = $ModuleBuilder.DefineType('Service.Trigger', 'Public, Class')

            #region Methods

            #region OpenSCManager Method
            $PInvokeMethod = $TypeBuilder.DefineMethod(
                'OpenSCManager', #Method Name
                [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
                [intptr], #Method Return Type
                [Type[]] @(
                    [string],
                    [string],  
                    [uint32]   
                ) #Method Parameters
            )

            $DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
            $FieldArray = [Reflection.FieldInfo[]] @(
                [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
                [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
                [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
                [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
            )

            $FieldValueArray = [Object[]] @(
                'OpenSCManagerA', #CASE SENSITIVE!!
                $True,
                $True,
                $True
            )

            $CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
                $DllImportConstructor,
                @('advapi32.dll'),
                $FieldArray,
                $FieldValueArray
            )

            $PInvokeMethod.SetCustomAttribute($CustomAttribute)
            #endregion OpenSCManager Method

            #region OpenService Method
            $PInvokeMethod = $TypeBuilder.DefineMethod(
                'OpenService', #Method Name
                [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
                [intptr], #Method Return Type
                [Type[]] @(
                    [intptr],
                    [string],  
                    [SERVICE_ACCESS]   
                ) #Method Parameters
            )

            $DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
            $FieldArray = [Reflection.FieldInfo[]] @(
                [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
                [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
                [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
                [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
                [Runtime.InteropServices.DllImportAttribute].GetField('CharSet')
            )

            $FieldValueArray = [Object[]] @(
                'OpenService', #CASE SENSITIVE!!
                $True,
                $False,
                $True,
                [System.Runtime.InteropServices.CharSet]::Auto
            )

            $CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
                $DllImportConstructor,
                @('advapi32.dll'),
                $FieldArray,
                $FieldValueArray
            )

            $PInvokeMethod.SetCustomAttribute($CustomAttribute)
            #endregion OpenService Method

            #region QueryServiceConfig2 Method
            $PInvokeMethod = $TypeBuilder.DefineMethod(
                'QueryServiceConfig2', #Method Name
                [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
                [bool], #Method Return Type
                [Type[]] @(
                    [intptr],
                    [uint32],  
                    [intptr] ,
                    [uint32],
                    [uint32].MakeByRefType()  
                ) #Method Parameters
            )

            $DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
            $FieldArray = [Reflection.FieldInfo[]] @(
                [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
                [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
                [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
                [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')            
            )

            $FieldValueArray = [Object[]] @(
                'QueryServiceConfig2A', #CASE SENSITIVE!!
                $True,
                $False,
                $True
            )

            $CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
                $DllImportConstructor,
                @('advapi32.dll'),
                $FieldArray,
                $FieldValueArray
            )

            $PInvokeMethod.SetCustomAttribute($CustomAttribute)
            #endregion QueryServiceConfig2 Method

            #region QueryServiceConfig Method
            $PInvokeMethod = $TypeBuilder.DefineMethod(
                'QueryServiceConfig', #Method Name
                [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
                [bool], #Method Return Type
                [Type[]] @(
                    [intptr],
                    [intptr],  
                    [uint32] ,
                    [uint32].MakeByRefType()  
                ) #Method Parameters
            )

            $DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
            $FieldArray = [Reflection.FieldInfo[]] @(
                [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
                [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
                [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
                [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')            
            )

            $FieldValueArray = [Object[]] @(
                'QueryServiceConfigA', #CASE SENSITIVE!!
                $True,
                $False,
                $True
            )

            $CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
                $DllImportConstructor,
                @('advapi32.dll'),
                $FieldArray,
                $FieldValueArray
            )

            $PInvokeMethod.SetCustomAttribute($CustomAttribute)
            #endregion QueryServiceConfig Method

            #region CloseServiceHandle Method
            $PInvokeMethod = $TypeBuilder.DefineMethod(
                'CloseServiceHandle', #Method Name
                [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
                [bool], #Method Return Type
                [Type[]] @(
                    [intptr] 
                ) #Method Parameters
            )

            $DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
            $FieldArray = [Reflection.FieldInfo[]] @(
                [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
                [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
                [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
                [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')              
            )

            $FieldValueArray = [Object[]] @(
                'CloseServiceHandle', #CASE SENSITIVE!!
                $True,
                $False,
                $True
            )

            $CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
                $DllImportConstructor,
                @('advapi32.dll'),
                $FieldArray,
                $FieldValueArray
            )

            $PInvokeMethod.SetCustomAttribute($CustomAttribute)
            #endregion CloseServiceHandle Method

            #region EnumServicesStatusEx Method
            $PInvokeMethod = $TypeBuilder.DefineMethod(
                'EnumServicesStatusEx', #Method Name
                [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
                [bool], #Method Return Type
                [Type[]] @(
                    [intptr],
                    [uint32],  
                    [uint32],
                    [uint32],
                    [intptr],
                    [uint32],
                    [uint32].MakeByRefType(),
                    [int].MakeByRefType(),
                    [uint32].MakeByRefType(),
                    [string]
                ) #Method Parameters
            )

            $DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
            $FieldArray = [Reflection.FieldInfo[]] @(
                [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
                [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
                [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
                [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
            )

            $FieldValueArray = [Object[]] @(
                'EnumServicesStatusExA', #CASE SENSITIVE!!
                $True,
                $True,
                $True
            )

            $CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
                $DllImportConstructor,
                @('advapi32.dll'),
                $FieldArray,
                $FieldValueArray
            )

            $PInvokeMethod.SetCustomAttribute($CustomAttribute)
            #endregion EnumServicesStatusEx Method

            #region QueryServiceStatusEx Method
            $PInvokeMethod = $TypeBuilder.DefineMethod(
                'QueryServiceStatusEx', #Method Name
                [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
                [bool], #Method Return Type
                [Type[]] @(
                    [intptr],
                    [uint32],  
                    [intptr],
                    [uint32],
                    [uint32].MakeByRefType()
                ) #Method Parameters
            )

            $DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
            $FieldArray = [Reflection.FieldInfo[]] @(
                [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
                [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
                [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
                [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
            )

            $FieldValueArray = [Object[]] @(
                'QueryServiceStatusEx', #CASE SENSITIVE!!
                $True,
                $True,
                $True
            )

            $CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
                $DllImportConstructor,
                @('advapi32.dll'),
                $FieldArray,
                $FieldValueArray
            )

            $PInvokeMethod.SetCustomAttribute($CustomAttribute)
            #endregion QueryServiceStatusEx Method

            #region EnumDependentServices Method
            $PInvokeMethod = $TypeBuilder.DefineMethod(
                'EnumDependentServices', #Method Name
                [Reflection.MethodAttributes] 'PrivateScope, Public, Static, HideBySig, PinvokeImpl', #Method Attributes
                [bool], #Method Return Type
                [Type[]] @(
                    [intptr],
                    [uint32],  
                    [intptr],
                    [uint32],
                    [uint32].MakeByRefType(),
                    [uint32].MakeByRefType()
                ) #Method Parameters
            )

            $DllImportConstructor = [Runtime.InteropServices.DllImportAttribute].GetConstructor(@([String]))
            $FieldArray = [Reflection.FieldInfo[]] @(
                [Runtime.InteropServices.DllImportAttribute].GetField('EntryPoint'),
                [Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')
                [Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling')
                [Runtime.InteropServices.DllImportAttribute].GetField('PreserveSig')
            )

            $FieldValueArray = [Object[]] @(
                'EnumDependentServicesA', #CASE SENSITIVE!!
                $True,
                $True,
                $True
            )

            $CustomAttribute = New-Object Reflection.Emit.CustomAttributeBuilder(
                $DllImportConstructor,
                @('advapi32.dll'),
                $FieldArray,
                $FieldValueArray
            )

            $PInvokeMethod.SetCustomAttribute($CustomAttribute)
            #endregion EnumDependentServices Method

            #endregion Methods

            [void]$TypeBuilder.CreateType()
        }
        #endregion Reflection

        #region Lookups
        $TRIGGER_SUBTYPE = @{
            NAMED_PIPE_EVENT_GUID = [guid]'1F81D131-3FAC-4537-9E0C-7E7B0C2F4B55'
            RPC_INTERFACE_EVENT_GUID = [guid]'BC90D167-9470-4139-A9BA-BE0BBBF5B74D'
            DOMAIN_JOIN_GUID = [guid]'1ce20aba-9851-4421-9430-1ddeb766e809'
            DOMAIN_LEAVE_GUID = [guid]'ddaf516e-58c2-4866-9574-c3b615d42ea1'
            FIREWALL_PORT_OPEN_GUID = [guid]'b7569e07-8421-4ee0-ad10-86915afdad09'
            FIREWALL_PORT_CLOSE_GUID = [guid]'a144ed38-8e12-4de4-9d96-e64740b1a524'
            MACHINE_POLICY_PRESENT_GUID = [guid]'659FCAE6-5BDB-4DA9-B1FF-CA2A178D46E0'
            NETWORK_MANAGER_FIRST_IP_ADDRESS_ARRIVAL_GUID = [guid]'4f27f2de-14e2-430b-a549-7cd48cbc8245'
            NETWORK_MANAGER_LAST_IP_ADDRESS_REMOVAL_GUID = [guid]'cc4ba62a-162e-4648-847a-b6bdf993e335'
            USER_POLICY_PRESENT_GUID = [guid]'54FB46C8-F089-464C-B1FD-59D1B62C3B50'
            ETW_PROVIDER_UUID = [guid]'d02a9c27-79b8-40d6-9b97-cf3f8b7b5d60'
            [guid]'1F81D131-3FAC-4537-9E0C-7E7B0C2F4B55' = 'NAMED_PIPE_EVENT'
            [guid]'BC90D167-9470-4139-A9BA-BE0BBBF5B74D' = 'RPC_INTERFACE_EVENT'
            [guid]'1ce20aba-9851-4421-9430-1ddeb766e809' = 'DOMAIN_JOIN'
            [guid]'ddaf516e-58c2-4866-9574-c3b615d42ea1' = 'DOMAIN_LEAVE'
            [guid]'b7569e07-8421-4ee0-ad10-86915afdad09' = 'FIREWALL_PORT_OPEN'
            [guid]'a144ed38-8e12-4de4-9d96-e64740b1a524' = 'FIREWALL_PORT_CLOSE'
            [guid]'659FCAE6-5BDB-4DA9-B1FF-CA2A178D46E0' = 'MACHINE_POLICY_PRESENT'
            [guid]'4f27f2de-14e2-430b-a549-7cd48cbc8245' = 'NETWORK_MANAGER_FIRST_IP_ADDRESS_ARRIVAL'
            [guid]'cc4ba62a-162e-4648-847a-b6bdf993e335' = 'NETWORK_MANAGER_LAST_IP_ADDRESS_REMOVAL'
            [guid]'54FB46C8-F089-464C-B1FD-59D1B62C3B50' = 'USER_POLICY_PRESENT'
            [guid]'d02a9c27-79b8-40d6-9b97-cf3f8b7b5d60' = 'ETW_PROVIDER'
        }
        #endregion Lookups
    }

    Process {
        If (-NOT $PSBoundParameters.ContainsKey('Computername')) {
            $Computername = $env:COMPUTERNAME            
        } 
        $Computername | ForEach {
            $Computer = $_
            #region Open SCManager
            Write-Verbose 'Opening Service Manager'
            $SCMHandle = [Service.Trigger]::OpenSCManager(
                $Computer, 
                [NullString]::Value, 
                ([SCM_ACCESS]::SC_MANAGER_CONNECT -BOR [SCM_ACCESS]::SC_MANAGER_ENUMERATE_SERVICE -BOR [SCM_ACCESS]::SC_MANAGER_QUERY_LOCK_STATUS)
            )
            $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
            If ($SCMHandle -eq [intptr]::Zero) {
                Write-Warning ("{0} ({1})" -f $LastError.Message,$LastError.NativeErrorCode)
                Break    
            }
            Write-Debug "SCManager Handle: $SCMHandle"
            #endregion Open SCManager

            $List = New-Object System.Collections.ArrayList

            If (-NOT $PSBoundParameters.ContainsKey('Name')) {
                #region Enum Services
                Write-Verbose 'Get all services'
                $BytesNeeded = 0
                $ServicesReturned = 0
                $ResumeHandle = 0
                $Return = [Service.Trigger]::EnumServicesStatusEx(
                    $SCMHandle,
                    [SC_ENUM_TYPE]::SC_ENUM_PROCESS_INFO,
                    [SERVICE_TYPE]$ServiceType,
                    [SERVICE_STATES]::SERVICE_ALL,
                    [IntPtr]::Zero,
                    0, # Current Buffer
                    [ref]$BytesNeeded,
                    [ref]$ServicesReturned,
                    [ref]$ResumeHandle,
                    [NullString]::Value
                )
                $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                Write-Debug "BytesNeeded: $BytesNeeded"
                If ($LastError.NativeErrorCode -eq 234) { #More data is available - Expected result
                    $Buffer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($BytesNeeded)
                    $Return = [Service.Trigger]::EnumServicesStatusEx(
                        $SCMHandle,
                        [SC_ENUM_TYPE]::SC_ENUM_PROCESS_INFO,
                        [SERVICE_TYPE]$ServiceType,
                        [SERVICE_STATES]::SERVICE_ALL,
                        $Buffer,
                        $BytesNeeded, # Current Buffer
                        [ref]$BytesNeeded,
                        [ref]$ServicesReturned,
                        [ref]$ResumeHandle,
                        [NullString]::Value
                    )
                    $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error() 
                    Write-Debug "ServicesReturned: $ServicesReturned"
                    If ($Return) {                    
                        $tempPointer = $Buffer
                        For ($i=0;$i -lt $ServicesReturned;$i++) {
                            #Write-Progress -Status 'Gathering Services' -PercentComplete (($i/$ServicesReturned)*100) -Activity "Pointer: $tempPointer"
                            If ([intptr]::Size -eq 8) {
                                # 64 bit
                                $Object = ([System.Runtime.InteropServices.Marshal]::PtrToStructure($tempPointer,[type][ENUM_SERVICE_STATUS_PROCESS]))
                                [intptr]$tempPointer = $tempPointer.ToInt64() + [System.Runtime.InteropServices.Marshal]::SizeOf([type][ENUM_SERVICE_STATUS_PROCESS])
                            } 
                            Else {
                                #32 bit
                                $Object = ([System.Runtime.InteropServices.Marshal]::PtrToStructure($tempPointer,[type][ENUM_SERVICE_STATUS_PROCESS]))
                                [intptr]$tempPointer = $tempPointer.ToInt32() + [System.Runtime.InteropServices.Marshal]::SizeOf([type][ENUM_SERVICE_STATUS_PROCESS])
                            }
                            Try {
                                $Controls = [SERVICE_CONTROL_CODE]$Object.ServiceStatusProcess.dwControlsAccepted
                            } 
                            Catch {
                                $Controls = $Object.ServiceStatusProcess.dwControlsAccepted
                            }
                            Try {
                                $Service_Type = [SERVICE_TYPE]$Object.ServiceStatusProcess.dwServiceType
                            } 
                            Catch {
                                $Service_Type = $Object.ServiceStatusProcess.dwServiceType
                            }
                            [void]$List.Add([pscustomobject]@{
                                Name = $Object.lpServiceName
                                Type = $Service_Type
                                State = [SERVICE_STATE]$Object.ServiceStatusProcess.dwCurrentState
                                Controls = $Controls
                                Win32ExitCode = $Object.ServiceStatusProcess.dwWin32ExitCode
                                ServiceExitCode = $Object.ServiceStatusProcess.dwServiceSpecificExitCode
                                CheckPoint = $Object.ServiceStatusProcess.dwCheckPoint
                                WaitHint = $Object.ServiceStatusProcess.dwWaitHint
                                ProcessID = $Object.ServiceStatusProcess.dwProcessId
                                ServiceFlags = [SERVICE_FLAGS]$Object.ServiceStatusProcess.dwServiceFlags
                            })
                        }
                    }         
                }
                #endregion Enum Services
            } 
            Else {
                $Name | ForEach {
                    $_Name = $_
                    Write-Verbose "Query single service: $_Name"

                    #region Open Service
                    $ServiceHandle = [Service.Trigger]::OpenService(
                        $SCMHandle,
                        $_Name,
                        [SERVICE_ACCESS]::SERVICE_QUERY_STATUS
                    )
                    #endregion Open Service

                    Write-Debug "Service Handle: $ServiceHandle"

                    #region Query Service
                    $BytesNeeded = 0
                    $Return = [Service.Trigger]::QueryServiceStatusEx(
                        $ServiceHandle,
                        0,
                        [intptr]::Zero,
                        $BytesNeeded,
                        [ref]$BytesNeeded
                    )
                    $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                    Write-Debug "Bytes Needed: $BytesNeeded"
                    If ($LastError.NativeErrorCode -eq 122) { #The data area passed to a system call is too small - This is expected!
                        Write-Verbose "Querying service"
                        $Buffer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($BytesNeeded)
                        $Return = [Service.Trigger]::QueryServiceStatusEx(
                            $ServiceHandle,
                            0,
                            $Buffer,
                            $BytesNeeded,
                            [ref]$BytesNeeded
                        )
                        $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                    } 
                    #endregion Query Service
                    If ($Return) {
                        $Object = [System.Runtime.InteropServices.Marshal]::PtrToStructure($Buffer, [type][SERVICE_STATUS_PROCESS])
                        Try {
                            $Controls = [SERVICE_CONTROL_CODE]$Object.dwControlsAccepted
                        } 
                        Catch {
                            $Controls = $Object.dwControlsAccepted
                        }
                        Try {
                            $Service_Type = [SERVICE_TYPE]$Object.dwServiceType
                        } 
                        Catch {
                            $Service_Type = $Object.dwServiceType
                        }
                        [void]$List.Add([pscustomobject]@{
                            Name = $_Name
                            Type = $Service_Type
                            State = [SERVICE_STATE]$Object.dwCurrentState
                            Controls = $Controls
                            Win32ExitCode = $Object.dwWin32ExitCode
                            ServiceExitCode = $Object.dwServiceSpecificExitCode
                            CheckPoint = $Object.dwCheckPoint
                            WaitHint = $Object.dwWaitHint
                            ProcessID = $Object.dwProcessId
                            ServiceFlags = [SERVICE_FLAGS]$Object.dwServiceFlags
                        })
                    }
                    [void][Service.Trigger]::CloseServiceHandle($ServiceHandle)
                }
            }
            Write-Verbose "Beginning iteration through services for more data"
            ForEach ($Service in $List) {
                #region Open Service
                $ServiceHandle = [Service.Trigger]::OpenService(
                    $SCMHandle,
                    $Service.Name,
                    [SERVICE_ACCESS]::SERVICE_QUERY_CONFIG
                )
                Write-Debug "ServiceHandle: $ServiceHandle"
                #endregion Open Service

                #region Query Service Required Privileges
                #Determine bytes needed
                [uint32]$BytesNeeded = $Null
                $Return = [Service.Trigger]::QueryServiceConfig2(
                    $ServiceHandle,
                    [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO,
                    [intptr]::Zero,
                    0,
                    [ref]$BytesNeeded
                )
                $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                If ($LastError.NativeErrorCode -eq 122) { 
                    #Buffer too small which is expected so we rerun this again with the expected buffer
                    $Pointer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($BytesNeeded)    
                    $Return = [Service.Trigger]::QueryServiceConfig2(
                        $ServiceHandle,
                        [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_REQUIRED_PRIVILEGES_INFO,
                        $Pointer,
                        $BytesNeeded,
                        [ref]$BytesNeeded
                    )
                    $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                    If (-NOT $Return) {
                        Write-Warning ("{0} ({1})" -f $LastError.Message,$LastError.NativeErrorCode)
                        Break    
                    }
                    #Build Struct from Pointer
                    $ServicePrivileges = [System.Runtime.InteropServices.Marshal]::PtrToStructure($Pointer,[type][SERVICE_REQUIRED_PRIVILEGES_INFO])
                    $P_Pointer = $ServicePrivileges.pmszRequiredPrivileges
                    $Remaining = $BytesNeeded
                    $Privileges = New-Object System.Collections.ArrayList
                    While ($Remaining -gt 0) {
                        $string = [System.Runtime.InteropServices.Marshal]::PtrToStringAnsi($P_Pointer)
                        If ($string.Length -gt 1) {
                            [void]$Privileges.Add($String)
                        } 
                        Else {
                            BREAK
                        } 
                        [intptr]$P_Pointer = $P_Pointer.ToInt64() + ($string.Length + 1) * ([System.Runtime.InteropServices.Marshal]::SizeOf([type][char]))
                        $Remaining = $Remaining = $string.Length
                    }

                    [System.Runtime.InteropServices.Marshal]::FreeHGlobal($Pointer)  
                }
                #endregion Query Service Required Privileges

                #region Query Service Failure Actions
                #Determine bytes needed
                [uint32]$BytesNeeded = $Null
                $Return = [Service.Trigger]::QueryServiceConfig2(
                    $ServiceHandle,
                    [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_FAILURE_ACTIONS,
                    [intptr]::Zero,
                    0,
                    [ref]$BytesNeeded
                )
                $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                If ($LastError.NativeErrorCode -eq 122) { 
                    #Buffer too small which is expected so we rerun this again with the expected buffer
                    $Pointer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($BytesNeeded)    
                    $Return = [Service.Trigger]::QueryServiceConfig2(
                        $ServiceHandle,
                        [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_FAILURE_ACTIONS,
                        $Pointer,
                        $BytesNeeded,
                        [ref]$BytesNeeded
                    )
                    $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                    If (-NOT $Return) {
                        Write-Warning ("{0} ({1})" -f $LastError.Message,$LastError.NativeErrorCode)
                        Break    
                    }

                    #Build Struct from Pointer
                    $FailureActions = [System.Runtime.InteropServices.Marshal]::PtrToStructure($Pointer,[type][SERVICE_FAILURE_ACTIONS])
                    $TPointer = $FailureActions.lpsaActions
                    $Actions = For ($i=0; $i -lt $FailureActions.cActions; $i++) {    
                        [System.Runtime.InteropServices.Marshal]::PtrToStructure($TPointer,[type][SC_ACTION])
                        [IntPtr]$TPointer = $TPointer.ToInt64() + [System.Runtime.InteropServices.Marshal]::SizeOf([type][SC_ACTION])
                    }        
                    $_FailureAction = New-Object FAILURE_ACTIONS 
                    $_FailureAction.ResetPeriod = $FailureActions.dwResetPeriod
                    $_FailureAction.RebootMessage = $FailureActions.lpRebootMsg
                    $_FailureAction.Command = $FailureActions.lpCommand
                    $_FailureAction.Actions = [SC_ACTION[]]$Actions
                    
                    [System.Runtime.InteropServices.Marshal]::FreeHGlobal($Pointer)  
                }
                #endregion Query Service Failure Actions

                #region Query Service Failure Actions Flag
                #Determine bytes needed
                [uint32]$BytesNeeded = $Null
                $Return = [Service.Trigger]::QueryServiceConfig2(
                    $ServiceHandle,
                    [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_FAILURE_ACTIONS_FLAG,
                    [intptr]::Zero,
                    0,
                    [ref]$BytesNeeded
                )
                $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                If ($LastError.NativeErrorCode -eq 122) { 
                    #Buffer too small which is expected so we rerun this again with the expected buffer
                    $Pointer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($BytesNeeded)    
                    $Return = [Service.Trigger]::QueryServiceConfig2(
                        $ServiceHandle,
                        [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_FAILURE_ACTIONS_FLAG,
                        $Pointer,
                        $BytesNeeded,
                        [ref]$BytesNeeded
                    )
                    $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                    If (-NOT $Return) {
                        Write-Warning ("{0} ({1})" -f $LastError.Message,$LastError.NativeErrorCode)
                        Break    
                    }
                    #Build Struct from Pointer
                    $FailureActionsFlag = [System.Runtime.InteropServices.Marshal]::PtrToStructure($Pointer,[type][SERVICE_FAILURE_ACTIONS_FLAG])
                    [System.Runtime.InteropServices.Marshal]::FreeHGlobal($Pointer)  
                }
                #endregion Query Service Failure Actions Flag

                #region Query Service Preferred Node
                #Determine bytes needed
                [uint32]$BytesNeeded = $Null
                $Return = [Service.Trigger]::QueryServiceConfig2(
                    $ServiceHandle,
                    [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_PREFERRED_NODE,
                    [intptr]::Zero,
                    0,
                    [ref]$BytesNeeded
                )
                $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                If ($LastError.NativeErrorCode -eq 122) { 
                    #Buffer too small which is expected so we rerun this again with the expected buffer
                    $Pointer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($BytesNeeded)    
                    $Return = [Service.Trigger]::QueryServiceConfig2(
                        $ServiceHandle,
                        [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_PREFERRED_NODE,
                        $Pointer,
                        $BytesNeeded,
                        [ref]$BytesNeeded
                    )
                    $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                    If (-NOT $Return) {
                        Write-Warning ("{0} ({1})" -f $LastError.Message,$LastError.NativeErrorCode)
                        Break    
                    }
                    #Build Struct from Pointer
                    $PreferredNode = [System.Runtime.InteropServices.Marshal]::PtrToStructure($Pointer,[type][SERVICE_PREFERRED_NODE_INFO])
                    [System.Runtime.InteropServices.Marshal]::FreeHGlobal($Pointer)  
                }
                #endregion Query Service Preferred Node

                #region Query Service Pre-Shutdown Timeout
                #Determine bytes needed
                [uint32]$BytesNeeded = $Null
                $Return = [Service.Trigger]::QueryServiceConfig2(
                    $ServiceHandle,
                    [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_PRESHUTDOWN_INFO,
                    [intptr]::Zero,
                    0,
                    [ref]$BytesNeeded
                )
                $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                If ($LastError.NativeErrorCode -eq 122) { 
                    #Buffer too small which is expected so we rerun this again with the expected buffer
                    $Pointer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($BytesNeeded)    
                    $Return = [Service.Trigger]::QueryServiceConfig2(
                        $ServiceHandle,
                        [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_PRESHUTDOWN_INFO,
                        $Pointer,
                        $BytesNeeded,
                        [ref]$BytesNeeded
                    )
                    $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                    If (-NOT $Return) {
                        Write-Warning ("{0} ({1})" -f $LastError.Message,$LastError.NativeErrorCode)
                        Break    
                    }
                    #Build Struct from Pointer
                    $ShutdownTimeout = [System.Runtime.InteropServices.Marshal]::PtrToStructure($Pointer,[type][SERVICE_PRESHUTDOWN_INFO])
                    [System.Runtime.InteropServices.Marshal]::FreeHGlobal($Pointer)  
                }
                #endregion Query Service Pre-Shutdown Timeout

                #region Query Service SID Type
                #Determine bytes needed
                [uint32]$BytesNeeded = $Null
                $Return = [Service.Trigger]::QueryServiceConfig2(
                    $ServiceHandle,
                    [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_SERVICE_SID_INFO,
                    [intptr]::Zero,
                    0,
                    [ref]$BytesNeeded
                )
                $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                If ($LastError.NativeErrorCode -eq 122) { 
                    #Buffer too small which is expected so we rerun this again with the expected buffer
                    $Pointer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($BytesNeeded)    
                    $Return = [Service.Trigger]::QueryServiceConfig2(
                        $ServiceHandle,
                        [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_SERVICE_SID_INFO,
                        $Pointer,
                        $BytesNeeded,
                        [ref]$BytesNeeded
                    )
                    $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                    If (-NOT $Return) {
                        Write-Warning ("{0} ({1})" -f $LastError.Message,$LastError.NativeErrorCode)
                        Break    
                    }
                    #Build Struct from Pointer
                    $ServiceSID = [System.Runtime.InteropServices.Marshal]::PtrToStructure($Pointer,[type][SERVICE_SID_INFO])
                    [System.Runtime.InteropServices.Marshal]::FreeHGlobal($Pointer)  
                }
                #endregion Query Service SID Type

                #region Query Service Description
                #Determine bytes needed
                [uint32]$BytesNeeded = $Null
                $Return = [Service.Trigger]::QueryServiceConfig2(
                    $ServiceHandle,
                    [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_DESCRIPTION,
                    [intptr]::Zero,
                    0,
                    [ref]$BytesNeeded
                )
                $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                If ($LastError.NativeErrorCode -eq 122) { 
                    #Buffer too small which is expected so we rerun this again with the expected buffer
                    $Pointer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($BytesNeeded)    
                    $Return = [Service.Trigger]::QueryServiceConfig2(
                        $ServiceHandle,
                        [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_DESCRIPTION,
                        $Pointer,
                        $BytesNeeded,
                        [ref]$BytesNeeded
                    )
                    $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                    If (-NOT $Return) {
                        Write-Warning ("{0} ({1})" -f $LastError.Message,$LastError.NativeErrorCode)
                        Break    
                    }
                    #Build Struct from Pointer
                    $Description = [System.Runtime.InteropServices.Marshal]::PtrToStructure($Pointer,[type][SERVICE_DESCRIPTION])
                    [System.Runtime.InteropServices.Marshal]::FreeHGlobal($Pointer)  
                }
                #endregion Query Service Description

                #region Query Service Configuration
                #Determine bytes needed
                [uint32]$BytesNeeded = $Null
                $Return = [Service.Trigger]::QueryServiceConfig(
                    $ServiceHandle,
                    [intptr]::Zero,
                    0,
                    [ref]$BytesNeeded
                )
                $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                If ($LastError.NativeErrorCode -eq 122) { 
                    #Buffer too small which is expected so we rerun this again with the expected buffer
                    $Pointer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($BytesNeeded)    
                    $Return = [Service.Trigger]::QueryServiceConfig(
                        $ServiceHandle,
                        $Pointer,
                        $BytesNeeded,
                        [ref]$BytesNeeded
                    )
                    $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                    If (-NOT $Return) {
                        Write-Warning ("{0} ({1})" -f $LastError.Message,$LastError.NativeErrorCode)
                        Break    
                    }
                    #Build Struct from Pointer
                    $ServiceConfiguration = [System.Runtime.InteropServices.Marshal]::PtrToStructure($Pointer,[type][QUERY_SERVICE_CONFIG])
                    [System.Runtime.InteropServices.Marshal]::FreeHGlobal($Pointer)  
                }
                #endregion Query Service Configuration

                #region Query Service Delayed AutoStart
                #Determine bytes needed
                [uint32]$BytesNeeded = $Null
                $Return = [Service.Trigger]::QueryServiceConfig2(
                    $ServiceHandle,
                    [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_DELAYED_AUTO_START_INFO,
                    [intptr]::Zero,
                    0,
                    [ref]$BytesNeeded
                )
                $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                If ($LastError.NativeErrorCode -eq 122) { 
                    #Buffer too small which is expected so we rerun this again with the expected buffer
                    $Pointer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($BytesNeeded)    
                    $Return = [Service.Trigger]::QueryServiceConfig2(
                        $ServiceHandle,
                        [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_DELAYED_AUTO_START_INFO,
                        $Pointer,
                        $BytesNeeded,
                        [ref]$BytesNeeded
                    )
                    $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                    If (-NOT $Return) {
                        Write-Warning ("{0} ({1})" -f $LastError.Message,$LastError.NativeErrorCode)
                        Break    
                    }
                    #Build Struct from Pointer
                    $AutoStart = [System.Runtime.InteropServices.Marshal]::PtrToStructure($Pointer,[type][SERVICE_DELAYED_AUTO_START_INFO])
                    [System.Runtime.InteropServices.Marshal]::FreeHGlobal($Pointer)  
                }
                #endregion Query Service Delayed AutoStart

                #region Query Service Triggers
                [uint32]$BytesNeeded = $Null
                $Return = [Service.Trigger]::QueryServiceConfig2(
                    $ServiceHandle,
                    [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_TRIGGER_INFO,
                    [intptr]::Zero,
                    0,
                    [ref]$BytesNeeded
                )
                $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                If ($LastError.NativeErrorCode -eq 122) { 
                    #Buffer too small which is expected so we rerun this again with the expected buffer
                    $Pointer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($BytesNeeded)    
                    $Return = [Service.Trigger]::QueryServiceConfig2(
                        $ServiceHandle,
                        [SERVICE_INFO_LEVEL]::SERVICE_CONFIG_TRIGGER_INFO,
                        $Pointer,
                        $BytesNeeded,
                        [ref]$BytesNeeded
                    )
                    $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                    If (-NOT $Return) {
                        Write-Warning ("{0} ({1})" -f $LastError.Message,$LastError.NativeErrorCode)
                        Break    
                    }
                    #Build Struct from Pointer
                    $TriggerInfo = [System.Runtime.InteropServices.Marshal]::PtrToStructure($Pointer,[type][SERVICE_TRIGGER_INFO])
                    $TPointer = $TriggerInfo.pTriggers
                    $Triggers = For ($i=0; $i -lt $TriggerInfo.cTriggers; $i++) {    
                        $ServiceTrigger = [System.Runtime.InteropServices.Marshal]::PtrToStructure($TPointer,[type][SERVICE_TRIGGER])
                        [IntPtr]$TPointer = $TPointer.ToInt64() + [System.Runtime.InteropServices.Marshal]::SizeOf([type][SERVICE_TRIGGER])
                        $GUID = [System.Runtime.InteropServices.Marshal]::PtrToStructure($ServiceTrigger.pTriggerSubType,[type][guid])
                        $Trigger = New-Object TRIGGER
                        $Trigger.TriggerType = $ServiceTrigger.dwTriggerType
                        $Trigger.Action = $ServiceTrigger.dwAction
                        $Trigger.SubType = $TRIGGER_SUBTYPE[$GUID]     
                        $Trigger
                    }
                }
                #endregion Query Service Triggers

                [void][Service.Trigger]::CloseServiceHandle($ServiceHandle)

                #region Open Service
                $ServiceHandle = [Service.Trigger]::OpenService(
                    $SCMHandle,
                    $Service.Name,
                    [SERVICE_ACCESS]::SERVICE_ENUMERATE_DEPENDENTS
                )
                $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                # TODO - Determine why certain services will not let you open handle with this access type without being admin; ie: RpcEptMapper
                Write-Debug "ServiceHandle: $ServiceHandle"
                #endregion Open Service

                #region Enum Dependant Services
                $D_Services = New-Object System.Collections.ArrayList
                Write-Verbose 'Get all dependant services'
                $BytesNeeded = 0
                $ServicesReturned = 0
                $Return = [Service.Trigger]::EnumDependentServices(
                    $ServiceHandle,
                    [SERVICE_STATES]::SERVICE_ALL,
                    [IntPtr]::Zero,
                    0, # Current Buffer
                    [ref]$BytesNeeded,
                    [ref]$ServicesReturned
                )
                $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error()
                Write-Debug "BytesNeeded<Dependant Services>: $BytesNeeded"
                Write-Debug "<Dependant Services>: $($LastError|select *|out-string)"
                If ($LastError.NativeErrorCode -eq 234) {
                    $Buffer = [System.Runtime.InteropServices.Marshal]::AllocHGlobal($BytesNeeded)
                    $Return = [Service.Trigger]::EnumDependentServices(
                        $ServiceHandle,
                        [SERVICE_STATES]::SERVICE_ALL,
                        $Buffer,
                        $BytesNeeded, # Current Buffer
                        [ref]$BytesNeeded,
                        [ref]$ServicesReturned
                    )
                    $LastError = [ComponentModel.Win32Exception][Runtime.InteropServices.Marshal]::GetLastWin32Error() 
                    Write-Debug "ServicesReturned: $ServicesReturned"
                    If ($Return) {                    
                        $tempPointer = $Buffer
                        For ($i=0;$i -lt $ServicesReturned;$i++) {
                            If ([intptr]::Size -eq 8) {
                                # 64 bit
                                $Object = ([System.Runtime.InteropServices.Marshal]::PtrToStructure($tempPointer,[type][ENUM_SERVICE_STATUS]))
                                [intptr]$tempPointer = $tempPointer.ToInt64() + [System.Runtime.InteropServices.Marshal]::SizeOf([type][ENUM_SERVICE_STATUS])
                                [void]$D_Services.Add($Object)
                            } 
                            Else {
                                #32 bit
                                $Object = ([System.Runtime.InteropServices.Marshal]::PtrToStructure($tempPointer,[type][ENUM_SERVICE_STATUS]))
                                [intptr]$tempPointer = $tempPointer.ToInt32() + [System.Runtime.InteropServices.Marshal]::SizeOf([type][ENUM_SERVICE_STATUS])
                                [void]$D_Services.Add($Object)
                            }
                        }
                    }         
                }
                #endregion Enum Dependant Services

                #region Display Object and Perform Cleanup
                Try {
                    $ServiceSIDType = [SERVICE_SID_TYPE]$ServiceSID.dwServiceSidType
                } 
                Catch {
                    $ServiceSIDType = $Null
                }
                Try {
                    $ServiceStartType = [SERVICE_START_TYPE]$ServiceConfiguration.dwStartType
                } 
                Catch {
                    $ServiceStartType = $Null
                }
                Try {
                    $ErrorControl = [ERROR_CONTROL]$ServiceConfiguration.dwErrorControl
                } 
                Catch {
                    $ErrorControl = $Null
                }
                $Object = [pscustomobject]@{
                    Name = $Service.Name
                    DisplayName = $ServiceConfiguration.lpDisplayName
                    Description = $Description.lpDescription
                    Triggers = $Triggers
                    IsDelayedAutoStart = $AutoStart.fDelayedAutostart
                    SIDType = $ServiceSIDType
                    Privileges = $Privileges
                    ShutdownTimeout = $ShutdownTimeout.dwPreshutdownTimeout
                    PreferredNode = $PreferredNode
                    FailureActionsFlag = $FailureActionsFlag.fFailureActionsOnNonCrashFailures
                    FailureActions = $_FailureAction
                    Type = $Service.Type
                    State = $Service.State
                    Controls = $Service.Controls
                    Win32ExitCode = $Service.Win32ExitCode
                    ServiceExitCode = $Service.ServiceExitCode
                    CheckPoint = $Service.CheckPoint
                    WaitHint = $Service.WaitHint
                    ProcessID = $Service.ProcessID
                    ServiceFlags = $Service.ServiceFlags
                    StartMode = $ServiceStartType
                    ErrorControl = $ErrorControl
                    FilePath = $ServiceConfiguration.lpBinaryPathName
                    LoadOrderGroup = $ServiceConfiguration.lpLoadOrderGroup
                    TagID = $ServiceConfiguration.dwTagId
                    Dependancies = $ServiceConfiguration.lpDependencies
                    StartName = $ServiceConfiguration.lpServiceStartName
                    DependantServices = $D_Services
                    Computername = $Computer
                }
                $Object.pstypenames.insert(0,'System.Service')
                $Object
                [void][Service.Trigger]::CloseServiceHandle($ServiceHandle)
                #endregion Display Object and Perform Cleanup
            }
        }
    }
}

function Set-ServiceConfig
{
    [CmdletBinding()]
    [OutputType([void])]
    param
    (
        #Name
        [Parameter(Mandatory=$true,ParameterSetName='NoRemoting_Default')]
        [string]$Name,

        #SIDType
        [Parameter(Mandatory=$false,ParameterSetName='NoRemoting_Default')]
        [ValidateSet('none','unrestricted','restricted')]
        [string]$SIDType,

        #StartType
        [Parameter(Mandatory=$false,ParameterSetName='NoRemoting_Default')]
        [ValidateSet('auto','demand','disabled')]
        [string]$StartType,

        #DelayedStart
        [Parameter(Mandatory=$false,ParameterSetName='NoRemoting_Default')]
        [ValidateSet($true,$false)]
        [bool]$IsDelayedAutoStart
    )
    
    Process
    {
        #Get Service
        try
        {
            Write-Verbose "Get Service started"
            
            $Service = Get-Service -Name $Name -ErrorAction Stop
      
            Write-Verbose "Get Service completed"
        }
        catch
        {
            Write-Error "Get Service failed. Details: $_" -ErrorAction 'Stop'
        }

        #Set Process
        try
        {
            Write-Verbose "Set Process started"
            
            if ($PSBoundParameters.ContainsKey('SIDType'))
            {
                Write-Verbose "Set Process in proress. Setting SIDType"
                $SCPath = Join-Path -Path ([environment]::GetFolderPath('System')) -ChildPath sc.exe
                Start-NewProcess -FilePath $SCPath -Arguments "sidtype $($Service.Name) $SIDType" -WaitTimeout 10 -ErrorAction Stop
            }
      
            Write-Verbose "Set Process completed" 
        }
        catch
        {
            Write-Error "Set Process failed. Details: $_" -ErrorAction 'Stop'
        }

        #Set Process StartType
        try
        {
            Write-Verbose "Set Process StartType started"
            
            if ($PSBoundParameters.ContainsKey('StartType') -or $PSBoundParameters.ContainsKey('IsDelayedAutoStart'))
            {
                Write-Verbose "Set Process StartType in proress. Setting startup type $StartType"
                $SCPath = Join-Path -Path ([environment]::GetFolderPath('System')) -ChildPath sc.exe
                if ($PSBoundParameters.ContainsKey('IsDelayedAutoStart')) 
                {
                    $startParam = "delayed-auto"
                }
                else 
                {
                    $startParam = $StartType
                }
                Start-NewProcess -FilePath $SCPath -Arguments "config $($Service.Name) start= $startParam" -WaitTimeout 10 -ErrorAction Stop
            }
      
            Write-Verbose "Set Process StartType completed"
        }
        catch
        {
            Write-Error "Set Process StartType failed. Details: $_" -ErrorAction 'Stop'
        }


    }
}