capturing error message from echo in cmd prompt
I'm writting out some text to a text file within a cmd batch script like such:
echo FlagValue=Y>>flag.txt
This normally works fine but occassionally if the text file is open by a different process, an error messgae is returned saying Access Denied. What I'd like to do is stop the batch file if an error occurs with something like:
if return_code GEQ 1 GOTO ERR
But can't find a return code fr开发者_如何学编程om echo command. Does one exist, or is there a better tactic to use to capture error message?
echo FlagValue=Y>>flag.txt || echo access_denied Ensure you have rights
or
echo FlagValue=Y>>flag.txt
if /i %errorlevel% NEQ 0 do (
echo access_denied Ensure you have rights
call sendmail.cmd
)
Sample:
C:\Users\Me\Desktop>echo Hello > MyFile.txt || echo ERROR
Access is denied.
ERROR
C:\Users\Me\Desktop>echo Hello > a.txt || echo ERROR
C:\Users\Me\Desktop>
Everytime you run a command the ERRORLEVEL environment variable is set to your command's return. So try echo %ERRORLEVEL% straight after you run your command. (Be careful as any command you run inbetween (including echo) will override the %ERRORLEVEL%.
Also, check these out for more information:
Can a batch file capture the exit codes of the commands it is invoking?
Batch Files - Error Handling
精彩评论