Search code examples
windowsbatch-filecmdnssm

Windows batch: find command and errorlevel


I'm trying to use the find command and errorlevel to evaluate the result of a command

Setlocal EnableDelayedExpansion
...
nssm status MyService | find "SERVICE_STOPPED"
if !errorlevel! equ 0 (
   echo MyService is not running
)

Since I know the command "nssm status MyService" returns "SERVICE_STOPPED" I would expect find to set the errorlevel to 0. Instead it's set to 1. Why?


Solution

  • A deleted answer showed the encoding of nssm output (I don't have it, so I can't verify). Every letter is encoded with two bytes (the second one being 0x00). So this (admittedly ugly) workaround should work:

    nssm status MyService | findstr "S.E.R.V.I.C.E._.S.T.O.P.P.E.D"
    if !errorlevel! equ 0 (
        echo MyService is not running
    )