skeetastax
skeetastax

Reputation: 1658

Powershell: How do I Start/Stop a Service and all RequiredServices that are not already running when started?

How do I achieve the following in a couple of Powershell one-liners (one to start, one to stop)?

I want to start service MyService in Powershell and also start all other services that are Required by MyService (i.e. services on which MyService Depends) that are not already started. I want to then be able to stop MyService and all the services I originally started with MyService, but not all other services on which MyService depends that were already started when I started MyService.

To clarify: If MyService Requires Service1, Service2 and Service3, and Service3 is also Required by UnrelatedService and is already running for UnrelatedService then I do not need/want to start Service3 in order to start MyService. Nor do I want to stop Service3 when I stop MyService because then UnrelatedService would fail. I do want to stop Service1 and Service2 when I stop MyService because they are Required only by MyService.

Secondly, I want to do this recursively, such that if there were other RequiredServices to Service1 and Service2 (recall Service3 is already running, therefore so are the services on which Service3 Depends) then I also want to start those other services on which Service1 and Service2 Depend and which are not already started.

Successful outcome would be that the list of [all services that are running after] I stop MyService is the same as the list of [all services that were running before] I started MyService and those on which it Depends.

My attempt

Get-Service MyService | 
   Select -expand RequiredServices | 
   Start-Service 

Start-Service : Service 'My Full Service Name (myservice)' cannot be started due to the following error: Cannot start service MyService on computer '.'. At line:1 char:57 + Get-Service MyService | Select -expand RequiredServices | Start-Service + + CategoryInfo : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service], ServiceCommandException + FullyQualifiedErrorId : CouldNotStartService,Microsoft.PowerShell.Commands.StartServiceCommand

Upvotes: 0

Views: 1049

Answers (1)

IT M
IT M

Reputation: 447

Sounds you need a Foreach-Object statement here. IMO your pipeline just does not recognize the expanded RequiredServices as a 'service' object.

Get-Service MyService | select -ExpandProperty RequiredServices | % {Start-Service $_.Name}

Or more verbose:

Get-Service MyService | Select-Object -ExpandProperty RequiredServices | ForEach-Object {Start-Service $_.Name}

After this you would be starting your service:

Start-Service MyService

Upvotes: 1

Related Questions