Search code examples
windowsbatch-filetaskkill

Batch - how do I store the status of a program in a variable?


I essentially want to write a script that can help a program restart itself if becomes 'not responding'. I then want to log this to a simple text file with the time so that I can check later how often it needed to restart, but how do I properly check the status and store that in a variable for the script to then decide whether to restart it or ignore it (as its otherwise either not running or running fine)?

I found that I can do something like.....

taskkill /im "myProgram.exe" /fi "STATUS eq NOT RESPONDING" /f >nul && start "" "C:\Program Files (x86)\myProgram\myProgram.exe"

which I got from Batch file to kill and restart not responding program

This is great and gets me part way there but when I append something to write to a log, I find it seems to write to the log anyway rather than only if the status is 'not responding'. It also doesn't offer me much flexibility to handle it in an if/else statement if I want to do something else with it.

This is what I tried with the appended bit....

taskkill /im "myProgram.exe" /fi "STATUS eq NOT RESPONDING" /f >nul && SET message=%time% %date% - myProgram is was not running so restarted it && ECHO %message% >> myProgram_restart_LOG.txt && START "" "C:\Program Files (x86)\myProgram\myProgram.exe"

(I guessed that && isn't conditional on the previous statement in the chain being successful but executes anyway regardless?)


Solution

  • && is conditional. The problem is that you are setting a variable and trying to access it directly. so either do call echo to access the variabe:

    taskkill /im "myProgram.exe" /fi "STATUS eq NOT RESPONDING" /f >nul && SET message=%time% %date% - myProgram is was not running so restarted it && call ECHO %message% >> myProgram_restart_LOG.txt & START "" "C:\Program Files (x86)\myProgram\myProgram.exe"
    

    Alternatively, just echo the message directly to the log file.

    taskkill /im "myProgram.exe" /fi "STATUS eq NOT RESPONDING" /f >nul && SET echo %time% %date% - myProgram is was not running so restarted it >> myProgram_restart_LOG.txt & START "" "C:\Program Files (x86)\myProgram\myProgram.exe"
    

    But I am not sure why you want to chain inside of a batch file, so I would do:

    taskkill /im "myProgram.exe" /fi "STATUS eq NOT RESPONDING" /f >nul
    if errorlevel 0 (
        echo %time% %date% - myProgram is was not running so restarted it>> myProgram_restart_LOG.txt
        START "" "C:\Program Files (x86)\myProgram\myProgram.exe"
    )