5

When using the following command to return information about a service to a file :

sc.exe query MyService >> MyFileLocation\MyFile.txt

I get the following information in the file :

SERVICE_NAME: MyService 
        TYPE               : 10  WIN32_OWN_PROCESS  
        STATE              : 4  RUNNING 
                                (STOPPABLE, NOT_PAUSABLE, ACCEPTS_SHUTDOWN)
        WIN32_EXIT_CODE    : 0  (0x0)
        SERVICE_EXIT_CODE  : 0  (0x0)
        CHECKPOINT         : 0x0
        WAIT_HINT          : 0x0

But I only need the State. I have checked the properties in the docs :

https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/sc-query

But I can't find anything that lets me return only the state. Is it possible to do and if so how to do it? Thanks in advance.

Niek Jonkman
  • 195
  • 1
  • 3
  • 8

2 Answers2

11

Using sc.exe is the cmd way.

Since you are using PowerShell, it is advised to use the Powershell Function Get-Service.

This allows you to use the following code:

(Get-Service MyService).status

This results in:

Running

To print it directly to a file, you can use:

(Get-Service MyService).status | out-file "MyLocation\MyFile.txt" -append

And given that we use powershell, you could even do something like this:

$status = (Get-Service MyService).status
"The status of MyService is $status" | out-file -path "MyLocation\MyFile.txt" -append
LPChip
  • 66,193
9

You may try the following:

sc.exe query MyService | select-string state >> MyFileLocation\MyFile.txt

The result should be:

STATE              : 4  RUNNING

With "pure" powershell:

Get-Service MyService | select Status