forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathService.cs
More file actions
2946 lines (2660 loc) · 109 KB
/
Copy pathService.cs
File metadata and controls
2946 lines (2660 loc) · 109 KB
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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#if !UNIX // Not built on Unix
using System;
using System.Collections.Generic;
using System.ComponentModel; // Win32Exception
using System.Diagnostics.CodeAnalysis;
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Runtime.InteropServices; // Marshal, DllImport
using System.Runtime.Serialization;
using System.Security.AccessControl;
using System.ServiceProcess;
using Dbg = System.Management.Automation.Diagnostics;
using DWORD = System.UInt32;
using NakedWin32Handle = System.IntPtr;
namespace Microsoft.PowerShell.Commands
{
#region ServiceBaseCommand
/// <summary>
/// This class implements the base for service commands.
/// </summary>
public abstract class ServiceBaseCommand : Cmdlet
{
#region Internal
/// <summary>
/// Confirm that the operation should proceed.
/// </summary>
/// <param name="service">Service object to be acted on.</param>
/// <returns>True if operation should continue, false otherwise.</returns>
protected bool ShouldProcessServiceOperation(ServiceController service)
{
return ShouldProcessServiceOperation(
service.DisplayName,
service.ServiceName);
}
/// <summary>
/// Confirm that the operation should proceed.
/// </summary>
/// <param name="displayName">Display name of service to be acted on.</param>
/// <param name="serviceName">Service name of service to be acted on.</param>
/// <returns>True if operation should continue, false otherwise.</returns>
protected bool ShouldProcessServiceOperation(
string displayName, string serviceName)
{
string name = StringUtil.Format(ServiceResources.ServiceNameForConfirmation,
displayName,
serviceName);
return ShouldProcess(name);
}
/// <summary>
/// Writes a non-terminating error.
/// </summary>
/// <param name="service"></param>
/// <param name="innerException"></param>
/// <param name="errorId"></param>
/// <param name="errorMessage"></param>
/// <param name="category"></param>
internal void WriteNonTerminatingError(
ServiceController service,
Exception innerException,
string errorId,
string errorMessage,
ErrorCategory category)
{
WriteNonTerminatingError(
service.ServiceName,
service.DisplayName,
service,
innerException,
errorId,
errorMessage,
category);
}
/// <summary>
/// Writes a non-terminating error.
/// </summary>
/// <param name="serviceName"></param>
/// <param name="displayName"></param>
/// <param name="targetObject"></param>
/// <param name="innerException"></param>
/// <param name="errorId"></param>
/// <param name="errorMessage"></param>
/// <param name="category"></param>
internal void WriteNonTerminatingError(
string serviceName,
string displayName,
object targetObject,
Exception innerException,
string errorId,
string errorMessage,
ErrorCategory category)
{
string message = StringUtil.Format(errorMessage,
serviceName,
displayName,
(innerException == null) ? category.ToString() : innerException.Message);
var exception = new ServiceCommandException(message, innerException);
exception.ServiceName = serviceName;
WriteError(new ErrorRecord(exception, errorId, category, targetObject));
}
internal void SetServiceSecurityDescriptor(
ServiceController service,
string securityDescriptorSddl,
NakedWin32Handle hService)
{
var rawSecurityDescriptor = new RawSecurityDescriptor(securityDescriptorSddl);
RawAcl rawDiscretionaryAcl = rawSecurityDescriptor.DiscretionaryAcl;
var discretionaryAcl = new DiscretionaryAcl(false, false, rawDiscretionaryAcl);
byte[] rawDacl = new byte[discretionaryAcl.BinaryLength];
discretionaryAcl.GetBinaryForm(rawDacl, 0);
rawSecurityDescriptor.DiscretionaryAcl = new RawAcl(rawDacl, 0);
byte[] securityDescriptorByte = new byte[rawSecurityDescriptor.BinaryLength];
rawSecurityDescriptor.GetBinaryForm(securityDescriptorByte, 0);
bool status = NativeMethods.SetServiceObjectSecurity(
hService,
SecurityInfos.DiscretionaryAcl,
securityDescriptorByte);
if (!status)
{
int lastError = Marshal.GetLastWin32Error();
Win32Exception exception = new(lastError);
bool accessDenied = exception.NativeErrorCode == NativeMethods.ERROR_ACCESS_DENIED;
WriteNonTerminatingError(
service,
exception,
nameof(ServiceResources.CouldNotSetServiceSecurityDescriptorSddl),
StringUtil.Format(ServiceResources.CouldNotSetServiceSecurityDescriptorSddl, service.ServiceName, exception.Message),
accessDenied ? ErrorCategory.PermissionDenied : ErrorCategory.InvalidOperation);
}
}
#endregion Internal
}
#endregion ServiceBaseCommand
#region MultipleServiceCommandBase
/// <summary>
/// This class implements the base for service commands which can
/// operate on multiple services.
/// </summary>
public abstract class MultipleServiceCommandBase : ServiceBaseCommand
{
#region Parameters
/// <summary>
/// The various process selection modes.
/// </summary>
internal enum SelectionMode
{
/// <summary>
/// Select all services.
/// </summary>
Default = 0,
/// <summary>
/// Select services matching the supplied names.
/// </summary>
DisplayName = 1,
/// <summary>
/// Select services based on pipeline input.
/// </summary>
InputObject = 2,
/// <summary>
/// Select services by Service name.
/// </summary>
ServiceName = 3
}
/// <summary>
/// Holds the selection mode setting.
/// </summary>
internal SelectionMode selectionMode;
/// <remarks>
/// The ServiceName parameter is declared in subclasses,
/// since it is optional for GetService and mandatory otherwise.
/// </remarks>
internal string[] serviceNames = null;
/// <summary>
/// Gets/sets an array of display names for services.
/// </summary>
[Parameter(ParameterSetName = "DisplayName", Mandatory = true)]
public string[] DisplayName
{
get
{
return displayNames;
}
set
{
displayNames = value;
selectionMode = SelectionMode.DisplayName;
}
}
internal string[] displayNames = null;
/// <summary>
/// Lets you include particular services. Services not matching
/// one of these (if specified) are excluded.
/// These are interpreted as either ServiceNames or DisplayNames
/// according to the parameter set.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public string[] Include
{
get
{
return include;
}
set
{
include = value;
}
}
internal string[] include = null;
/// <summary>
/// Lets you exclude particular services. Services matching
/// one of these (if specified) are excluded.
/// These are interpreted as either ServiceNames or DisplayNames
/// according to the parameter set.
/// </summary>
[Parameter]
[ValidateNotNullOrEmpty]
public string[] Exclude
{
get
{
return exclude;
}
set
{
exclude = value;
}
}
internal string[] exclude = null;
// 1054295-2004/12/01-JonN This also works around 1054295.
/// <summary>
/// If the input is a stream of [collections of]
/// ServiceController objects, we bypass the ServiceName and
/// DisplayName parameters and read the ServiceControllers
/// directly. This allows us to deal with services which
/// have wildcard characters in their name (servicename or
/// displayname).
/// </summary>
/// <value>ServiceController objects</value>
[Parameter(ParameterSetName = "InputObject", ValueFromPipeline = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public ServiceController[] InputObject
{
get
{
return _inputObject;
}
set
{
_inputObject = value;
selectionMode = SelectionMode.InputObject;
}
}
private ServiceController[] _inputObject = null;
#endregion Parameters
#region Internal
/// <summary>
/// Gets an array of all services.
/// </summary>
/// <value>
/// An array of <see cref="ServiceController"/> components that represents all the service resources.
/// </value>
/// <exception cref="System.Security.SecurityException">
/// MSDN does not document the list of exceptions,
/// but it is reasonable to expect that SecurityException is
/// among them. Errors here will terminate the cmdlet.
/// </exception>
internal ServiceController[] AllServices => _allServices ??= ServiceController.GetServices();
private ServiceController[] _allServices;
internal ServiceController GetOneService(string nameOfService)
{
Dbg.Assert(!WildcardPattern.ContainsWildcardCharacters(nameOfService), "Caller should verify that nameOfService doesn't contain wildcard characters");
try
{
var sc = new ServiceController(nameOfService);
// This will throw if the service doesn't exist
var unused = sc.Status;
// No exception, then this is an existing, valid service. Return it.
return sc;
}
catch (InvalidOperationException) { }
catch (ArgumentException) { }
return null;
}
/// <summary>
/// Retrieve the list of all services matching the ServiceName,
/// DisplayName, Include and Exclude parameters, sorted by ServiceName.
/// </summary>
/// <returns></returns>
internal List<ServiceController> MatchingServices()
{
List<ServiceController> matchingServices;
switch (selectionMode)
{
case SelectionMode.DisplayName:
matchingServices = MatchingServicesByDisplayName();
break;
case SelectionMode.InputObject:
matchingServices = MatchingServicesByInput();
break;
default:
matchingServices = MatchingServicesByServiceName();
break;
}
// 2004/12/16 Note that the services will be sorted
// before being stopped. JimTru confirms that this is OK.
matchingServices.Sort(ServiceComparison);
return matchingServices;
}
// sort by servicename
private static int ServiceComparison(ServiceController x, ServiceController y)
{
return string.Compare(x.ServiceName, y.ServiceName, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Retrieves the list of all services matching the ServiceName,
/// Include and Exclude parameters.
/// Generates a non-terminating error for each specified
/// service name which is not found even though it contains
/// no wildcards.
/// </summary>
/// <returns></returns>
/// <remarks>
/// We do not use the ServiceController(string serviceName)
/// constructor variant, since the resultant
/// ServiceController.ServiceName is the provided serviceName
/// even when that differs from the real ServiceName by case.
/// </remarks>
private List<ServiceController> MatchingServicesByServiceName()
{
List<ServiceController> matchingServices = new();
if (serviceNames == null)
{
foreach (ServiceController service in AllServices)
{
IncludeExcludeAdd(matchingServices, service, false);
}
return matchingServices;
}
foreach (string pattern in serviceNames)
{
bool found = false;
if (WildcardPattern.ContainsWildcardCharacters(pattern))
{
WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
foreach (ServiceController service in AllServices)
{
if (!wildcard.IsMatch(service.ServiceName))
continue;
found = true;
IncludeExcludeAdd(matchingServices, service, true);
}
}
else
{
ServiceController service = GetOneService(pattern);
if (service != null)
{
found = true;
IncludeExcludeAdd(matchingServices, service, true);
}
}
if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern))
{
WriteNonTerminatingError(
pattern,
string.Empty,
pattern,
null,
"NoServiceFoundForGivenName",
ServiceResources.NoServiceFoundForGivenName,
ErrorCategory.ObjectNotFound);
}
}
return matchingServices;
}
/// <summary>
/// Retrieves the list of all services matching the DisplayName,
/// Include and Exclude parameters.
/// Generates a non-terminating error for each specified
/// display name which is not found even though it contains
/// no wildcards.
/// </summary>
/// <returns></returns>
private List<ServiceController> MatchingServicesByDisplayName()
{
List<ServiceController> matchingServices = new();
if (DisplayName == null)
{
Diagnostics.Assert(false, "null DisplayName");
throw PSTraceSource.NewInvalidOperationException();
}
foreach (string pattern in DisplayName)
{
WildcardPattern wildcard =
WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
bool found = false;
foreach (ServiceController service in AllServices)
{
if (!wildcard.IsMatch(service.DisplayName))
continue;
found = true;
IncludeExcludeAdd(matchingServices, service, true);
}
if (!found && !WildcardPattern.ContainsWildcardCharacters(pattern))
{
WriteNonTerminatingError(
string.Empty,
pattern,
pattern,
null,
"NoServiceFoundForGivenDisplayName",
ServiceResources.NoServiceFoundForGivenDisplayName,
ErrorCategory.ObjectNotFound);
}
}
return matchingServices;
}
/// <summary>
/// Retrieves the list of all services matching the InputObject,
/// Include and Exclude parameters.
/// </summary>
/// <returns></returns>
private List<ServiceController> MatchingServicesByInput()
{
List<ServiceController> matchingServices = new();
if (InputObject == null)
{
Diagnostics.Assert(false, "null InputObject");
throw PSTraceSource.NewInvalidOperationException();
}
foreach (ServiceController service in InputObject)
{
service.Refresh();
IncludeExcludeAdd(matchingServices, service, false);
}
return matchingServices;
}
/// <summary>
/// Add <paramref name="service"/> to <paramref name="list"/>,
/// but only if it passes the Include and Exclude filters (if present)
/// and (if <paramref name="checkDuplicates"/>) if it is not
/// already on <paramref name="list"/>.
/// </summary>
/// <param name="list">List of services.</param>
/// <param name="service">Service to add to list.</param>
/// <param name="checkDuplicates">Check list for duplicates.</param>
private void IncludeExcludeAdd(
List<ServiceController> list,
ServiceController service,
bool checkDuplicates)
{
if (include != null && !Matches(service, include))
return;
if (exclude != null && Matches(service, exclude))
return;
if (checkDuplicates)
{
foreach (ServiceController sc in list)
{
if (sc.ServiceName == service.ServiceName &&
sc.MachineName == service.MachineName)
{
return;
}
}
}
list.Add(service);
}
/// <summary>
/// Check whether <paramref name="service"/> matches the list of
/// patterns in <paramref name="matchList"/>.
/// </summary>
/// <param name="service"></param>
/// <param name="matchList"></param>
/// <returns></returns>
private bool Matches(ServiceController service, string[] matchList)
{
if (matchList == null)
throw PSTraceSource.NewArgumentNullException(nameof(matchList));
string serviceID = (selectionMode == SelectionMode.DisplayName)
? service.DisplayName
: service.ServiceName;
foreach (string pattern in matchList)
{
WildcardPattern wildcard = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase);
if (wildcard.IsMatch(serviceID))
return true;
}
return false;
}
#endregion Internal
}
#endregion MultipleServiceCommandBase
#region GetServiceCommand
/// <summary>
/// This class implements the get-service command.
/// </summary>
[Cmdlet(VerbsCommon.Get, "Service", DefaultParameterSetName = "Default",
HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096496", RemotingCapability = RemotingCapability.SupportedByCommand)]
[OutputType(typeof(ServiceController))]
public sealed class GetServiceCommand : MultipleServiceCommandBase
{
#region Parameters
/// <summary>
/// Gets/sets an array of service names.
/// </summary>
/// <remarks>
/// The ServiceName parameter is declared in subclasses,
/// since it is optional for GetService and mandatory otherwise.
/// </remarks>
[Parameter(Position = 0, ParameterSetName = "Default", ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
[ValidateNotNullOrEmpty()]
[Alias("ServiceName")]
public string[] Name
{
get
{
return serviceNames;
}
set
{
serviceNames = value;
selectionMode = SelectionMode.ServiceName;
}
}
/// <summary>
/// This returns the DependentServices of the specified service.
/// </summary>
[Parameter]
[Alias("DS")]
public SwitchParameter DependentServices { get; set; }
/// <summary>
/// This returns the ServicesDependedOn of the specified service.
/// </summary>
[Parameter]
[Alias("SDO", "ServicesDependedOn")]
public SwitchParameter RequiredServices { get; set; }
#endregion Parameters
#region Overrides
/// <summary>
/// Write the service objects.
/// </summary>
protected override void ProcessRecord()
{
nint scManagerHandle = nint.Zero;
if (!DependentServices && !RequiredServices)
{
// As Get-Service only works on local services we get this once
// to retrieve extra properties added by PowerShell.
scManagerHandle = NativeMethods.OpenSCManagerW(
lpMachineName: null,
lpDatabaseName: null,
dwDesiredAccess: NativeMethods.SC_MANAGER_CONNECT);
if (scManagerHandle == nint.Zero)
{
Win32Exception exception = new();
string message = StringUtil.Format(ServiceResources.FailToOpenServiceControlManager, exception.Message);
ServiceCommandException serviceException = new ServiceCommandException(message, exception);
ErrorRecord err = new ErrorRecord(
serviceException,
"FailToOpenServiceControlManager",
ErrorCategory.PermissionDenied,
null);
ThrowTerminatingError(err);
}
}
try
{
foreach (ServiceController service in MatchingServices())
{
if (!DependentServices.IsPresent && !RequiredServices.IsPresent)
{
WriteObject(AddProperties(scManagerHandle, service));
}
else
{
if (DependentServices.IsPresent)
{
foreach (ServiceController dependantserv in service.DependentServices)
{
WriteObject(dependantserv);
}
}
if (RequiredServices.IsPresent)
{
foreach (ServiceController servicedependedon in service.ServicesDependedOn)
{
WriteObject(servicedependedon);
}
}
}
}
}
finally
{
if (scManagerHandle != nint.Zero)
{
bool succeeded = NativeMethods.CloseServiceHandle(scManagerHandle);
Diagnostics.Assert(succeeded, "SCManager handle close failed");
}
}
}
#endregion Overrides
#nullable enable
/// <summary>
/// Writes a verbose message when a service property query fails.
/// </summary>
/// <param name="serviceName">Name of the service.</param>
/// <param name="propertyName">Name of the property that failed to be queried.</param>
private void WriteServicePropertyError(string serviceName, string propertyName)
{
Win32Exception e = new(Marshal.GetLastWin32Error());
WriteVerbose(
StringUtil.Format(
ServiceResources.CouldNotGetServiceProperty,
serviceName,
propertyName,
e.Message));
}
/// <summary>
/// Adds UserName, Description, BinaryPathName, DelayedAutoStart and StartupType to a ServiceController object.
/// </summary>
/// <param name="scManagerHandle">Handle to the local SCManager instance.</param>
/// <param name="service"></param>
/// <returns>ServiceController as PSObject with UserName, Description and StartupType added.</returns>
private PSObject AddProperties(nint scManagerHandle, ServiceController service)
{
NakedWin32Handle hService = nint.Zero;
// As these are optional values, a failure due to permissions or
// other problem is ignored and the properties are set to null.
bool? isDelayedAutoStart = null;
string? binPath = null;
string? description = null;
string? startName = null;
ServiceStartupType startupType = ServiceStartupType.InvalidValue;
try
{
// We don't use service.ServiceHandle as that requests
// SERVICE_ALL_ACCESS when we only need SERVICE_QUERY_CONFIG.
hService = NativeMethods.OpenServiceW(
scManagerHandle,
service.ServiceName,
NativeMethods.SERVICE_QUERY_CONFIG
);
if (hService != nint.Zero)
{
if (NativeMethods.QueryServiceConfig2(
hService,
NativeMethods.SERVICE_CONFIG_DESCRIPTION,
out NativeMethods.SERVICE_DESCRIPTIONW descriptionInfo))
{
description = descriptionInfo.lpDescription;
}
else
{
WriteServicePropertyError(service.ServiceName, nameof(NativeMethods.SERVICE_DESCRIPTIONW));
}
if (NativeMethods.QueryServiceConfig2(
hService,
NativeMethods.SERVICE_CONFIG_DELAYED_AUTO_START_INFO,
out NativeMethods.SERVICE_DELAYED_AUTO_START_INFO autostartInfo))
{
isDelayedAutoStart = autostartInfo.fDelayedAutostart;
}
else
{
WriteServicePropertyError(service.ServiceName, nameof(NativeMethods.SERVICE_DELAYED_AUTO_START_INFO));
}
if (NativeMethods.QueryServiceConfig(
hService,
out NativeMethods.QUERY_SERVICE_CONFIG serviceInfo))
{
binPath = serviceInfo.lpBinaryPathName;
startName = serviceInfo.lpServiceStartName;
if (isDelayedAutoStart.HasValue)
{
startupType = NativeMethods.GetServiceStartupType(
(ServiceStartMode)serviceInfo.dwStartType,
isDelayedAutoStart.Value);
}
}
else
{
WriteServicePropertyError(service.ServiceName, nameof(NativeMethods.QUERY_SERVICE_CONFIG));
}
}
else
{
// handle when OpenServiceW itself fails:
WriteServicePropertyError(service.ServiceName, nameof(NativeMethods.SERVICE_QUERY_CONFIG));
}
}
finally
{
if (hService != IntPtr.Zero)
{
bool succeeded = NativeMethods.CloseServiceHandle(hService);
Diagnostics.Assert(succeeded, "Failed to close service handle");
}
}
PSObject serviceAsPSObj = PSObject.AsPSObject(service);
PSNoteProperty noteProperty = new("UserName", startName);
serviceAsPSObj.Properties.Add(noteProperty, true);
serviceAsPSObj.TypeNames.Insert(0, "System.Service.ServiceController#UserName");
noteProperty = new PSNoteProperty("Description", description);
serviceAsPSObj.Properties.Add(noteProperty, true);
serviceAsPSObj.TypeNames.Insert(0, "System.Service.ServiceController#Description");
noteProperty = new PSNoteProperty("DelayedAutoStart", isDelayedAutoStart);
serviceAsPSObj.Properties.Add(noteProperty, true);
serviceAsPSObj.TypeNames.Insert(0, "System.Service.ServiceController#DelayedAutoStart");
noteProperty = new PSNoteProperty("BinaryPathName", binPath);
serviceAsPSObj.Properties.Add(noteProperty, true);
serviceAsPSObj.TypeNames.Insert(0, "System.Service.ServiceController#BinaryPathName");
noteProperty = new PSNoteProperty("StartupType", startupType);
serviceAsPSObj.Properties.Add(noteProperty, true);
serviceAsPSObj.TypeNames.Insert(0, "System.Service.ServiceController#StartupType");
return serviceAsPSObj;
}
}
#nullable disable
#endregion GetServiceCommand
#region ServiceOperationBaseCommand
/// <summary>
/// This class implements the base for service commands which actually
/// act on the service(s).
/// </summary>
public abstract class ServiceOperationBaseCommand : MultipleServiceCommandBase
{
#region Parameters
/// <summary>
/// Gets/sets an array of service names.
/// </summary>
/// <remarks>
/// The ServiceName parameter is declared in subclasses,
/// since it is optional for GetService and mandatory otherwise.
/// </remarks>
[Parameter(Position = 0, ParameterSetName = "Default", Mandatory = true, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
[Alias("ServiceName")]
public string[] Name
{
get
{
return serviceNames;
}
set
{
serviceNames = value;
selectionMode = SelectionMode.ServiceName;
}
}
/// <summary>
/// Service controller objects.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ParameterSetName = "InputObject", ValueFromPipeline = true)]
[ValidateNotNullOrEmpty]
[SuppressMessage("Microsoft.Performance", "CA1819:PropertiesShouldNotReturnArrays")]
public new ServiceController[] InputObject
{
get
{
return base.InputObject;
}
set
{
base.InputObject = value;
}
}
/// <summary>
/// Specifies whether to write the objects successfully operated upon
/// to the success stream.
/// </summary>
[Parameter]
public SwitchParameter PassThru { get; set; }
#endregion Parameters
#region Internal
/// <summary>
/// Waits forever for the service to reach the desired status, but
/// writes a string to WriteWarning every 2 seconds.
/// </summary>
/// <param name="serviceController">Service on which to operate.</param>
/// <param name="targetStatus">Desired status.</param>
/// <param name="pendingStatus">
/// This is the expected status while the operation is incomplete.
/// If the service is in some other state, this means that the
/// operation failed.
/// </param>
/// <param name="resourceIdPending">
/// resourceId for a string to be written to verbose stream
/// every 2 seconds
/// </param>
/// <param name="errorId">
/// errorId for a nonterminating error if operation fails
/// </param>
/// <param name="errorMessage">
/// errorMessage for a nonterminating error if operation fails
/// </param>
/// <returns>True if action succeeded.</returns>
/// <exception cref="PipelineStoppedException">
/// WriteWarning will throw this if the pipeline has been stopped.
/// This means that the delay between hitting CTRL-C and stopping
/// the cmdlet should be 2 seconds at most.
/// </exception>
internal bool DoWaitForStatus(
ServiceController serviceController,
ServiceControllerStatus targetStatus,
ServiceControllerStatus pendingStatus,
string resourceIdPending,
string errorId,
string errorMessage)
{
while (true)
{
try
{
// ServiceController.Start will return before the service is actually started
// This API will wait forever
serviceController.WaitForStatus(
targetStatus,
new TimeSpan(20000000) // 2 seconds
);
return true; // service reached target status
}
catch (System.ServiceProcess.TimeoutException) // still waiting
{
if (serviceController.Status != pendingStatus
// NTRAID#Windows Out Of Band Releases-919945-2005/09/27-JonN
// Close window where service could complete at
// just the wrong time
&& serviceController.Status != targetStatus)
{
WriteNonTerminatingError(serviceController, null,
errorId,
errorMessage,
ErrorCategory.OpenError);
return false;
}
string message = StringUtil.Format(resourceIdPending,
serviceController.ServiceName,
serviceController.DisplayName
);
// will throw PipelineStoppedException if user hit CTRL-C
WriteWarning(message);
}
}
}
/// <summary>
/// This will start the service.
/// </summary>
/// <param name="serviceController">Service to start.</param>
/// <returns>True if-and-only-if the service was started.</returns>
internal bool DoStartService(ServiceController serviceController)
{
Exception exception = null;
try
{
serviceController.Start();
}
catch (Win32Exception e)
{
if (e.NativeErrorCode != NativeMethods.ERROR_SERVICE_ALREADY_RUNNING)
exception = e;
}
catch (InvalidOperationException e)
{
if (e.InnerException is not Win32Exception eInner
|| eInner.NativeErrorCode != NativeMethods.ERROR_SERVICE_ALREADY_RUNNING)
{
exception = e;
}
}
if (exception != null)
{
// This service refused to accept the start command,
// so write a non-terminating error.
WriteNonTerminatingError(serviceController,
exception,
"CouldNotStartService",
ServiceResources.CouldNotStartService,
ErrorCategory.OpenError);
return false;
}
// ServiceController.Start will return
// before the service is actually started.
if (!DoWaitForStatus(
serviceController,
ServiceControllerStatus.Running,
ServiceControllerStatus.StartPending,
ServiceResources.StartingService,
"StartServiceFailed",
ServiceResources.StartServiceFailed))
{
return false;
}
return true;
}
/// <summary>
/// This will stop the service.
/// </summary>
/// <param name="serviceController">Service to stop.</param>
/// <param name="force">Stop dependent services.</param>
/// <param name="waitForServiceToStop"></param>
/// <returns>True if-and-only-if the service was stopped.</returns>
internal List<ServiceController> DoStopService(ServiceController serviceController, bool force, bool waitForServiceToStop)
{