I need to run a command line check to see if a service is stopped, and if it is, start it. I can not just start it because then I get a bad resultcode and the SCCM task sequence I need it for fails.

Here's what I thought should've done the trick but didn't:

IF NOT ('sc query "bits"^| find "RUNNING"')=="" sc start "bits"

The error I get is: query was unexpected at this time.

I'd like to do this in a single line.

Thanks already

2 Answers 2


Dunno whether you would consider this one line as it uses the & character, but what about :

sc query bits | find "RUNNING" & if errorlevel 1 sc start bits
  • testing it now. I kind of doubt it'll work, because as soon as something gives an error, the whole thing will fail. In this case, you just act upon the error, but the error still occurs... I think? Will let you know if it works! Oct 25, 2010 at 11:12
  • If whatever is running this command treats this all as one line, then it should work as the errorlevel returned will normally be 0. If the status is already running, then find command will return 0, otherwise the sc start bits will return 0 (assuming the service starts).
    – sgmoore
    Oct 26, 2010 at 8:41
  • The other option you have is to write a longer batch file and then use one of the bat to exe compiler/converters.
    – sgmoore
    Oct 26, 2010 at 8:46
  • Seems this does the trick, shame my solution doesn't work because I can't execute this in WinPE before the OS loads for some reason Oct 29, 2010 at 7:52

If you are willing to use PowerShell, you can do this:

Get-Service | Where-Object {$_.status -eq "stopped" -and $_.name -eq "MySvcName"} | Start-Service

You just have to be sure to pass the service name, not the display name, to the where-object command. You can see the two names on the service propery page.


If you want a one-liner in cmd, you can embed the powershell one liner in a cmd one liner:

powershell -Command "& {Get-Service | Where-Object {$_.status -eq \"stopped\" -and $_.name -eq \"MySvcName\"} | Start-Service }"
  • 1
    @Hannes, I've updated to show how you can call the powershell commands from cmd
    – dsolimano
    Oct 27, 2010 at 15:15
  • thanks a lot, however PS won't be installed on these computers and there's no real reason to install it right now. Oct 29, 2010 at 7:52

You must log in to answer this question.

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