RonyA
RonyA

Reputation: 635

Not able to get status of service powershell

I have a list of services in a text file. I am using that from Get-Content like below. But its not working while taking service from file. When just using get-service Service* and using below code it works. Please help me to fix the code with changes . Set-Service Line and the if condition line as .Status and .Name not working

$TEST= Get-Content "Somelocation\service.txt"

foreach ($service in $TEST )
{

    if($**service.Status** -eq "Stopped")
    {
              Set-Service $**service.Name** -StartupType Manual
              "Starting  $service"
              start-service $service -WarningAction SilentlyContinue

    }
    else
    {
        "$service was already started."
    }
}

Note: I tried using ** to make word bold but not happen inside code

Upvotes: 1

Views: 208

Answers (1)

Martin Brandl
Martin Brandl

Reputation: 59021

You have to retrieve the service instance using the Get-Service cmdlet in order to query the status:

$TEST= Get-Content "Somelocation\service.txt"

foreach ($service in $TEST )
{
    $serviceInstance = Get-Service $service
    if($serviceInstance.Status -eq "Stopped")
    {
              Set-Service $service -StartupType Manual
              "Starting  $service"
              $serviceInstance.Start()
    }
    else
    {
        "$service was already started."
    }
}

Upvotes: 2

Related Questions