how to start a installed service wth powerhell and set the startup type for that service

Viewed 65

i want to start a service with a certain name eg. test. the things i need to do is:

  1. check if service is installed
  2. change startup type to automatic
  3. start the service

i have tried the following command but that is not working: get-service testAM* | Set-Service -name testAM* -StartupType automatic |Start-Service TestAM*

1 Answers

You're on the right track already. Set-Service is one of those cmdlets that consumes the object once completed. So, you just have to tell it to move on down the pipeline using -Passthru.

Get-Service -DisplayName testAM* | Set-Service -StartupType Automatic -PassThru | Start-Service -PassThru

There's also no need to re-specify the name on Set-Service as it accepts the object being output by Get-Service. InputObjects accepted by Set-Service are as follows:

  • System.String
  • System.String[]
  • System.ServiceProcess.ServiceController

Take a look at Get-Help Get-Service -ShowWindow, and Get-Help Set-Service -ShowWindow to see how I got the objects that it accepts, just scroll down to "Inputs", and "Outputs".

EDIT: Just saw you'd like to check if they exists. You can add some simple if(){}, and else{} logic:

$Service_Name  = "testAM*"
$Test_Services = Get-Service -DisplayName $Service_Name
    if($Test_Services){
        #$Test_Services | Set-Service -StartupType Automatic -PassThru | Start-Service -PassThru
        foreach($Service in $Test_Services){
            "$($Service.DisplayName) exists!"
            #or:
            #Slower way of setting the service and starting them
            #Set-Service -InputObject $Service -StartupType Automatic -PassThru | Start-Service -PassThru
        }
    } else {
        "No services with name '$Service_Name' exist!:("
    }
Related