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.

2 Answers 2

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
1
  • Thanks, works as expected! Cheers. Commented Dec 21, 2021 at 12:25
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
2
  • Thanks for the tip! Why use out-file instead of >> though? Commented Dec 21, 2021 at 13:34
  • 1
    Its the powershell way of things, and thus allows more flexibility in the long run. out-file can also handle way more outputs than >> can, as >> expects text, where out-file will try to convert it into something readable if it needs to do that. See also: docs.microsoft.com/en-us/powershell/module/…
    – LPChip
    Commented Dec 21, 2021 at 13:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .