i'm trying to write a simple if exists in batch but getting an error.
GOTO was unexpected at this time.
Below is my code:
::find /i "The OU has been created" error_ou.log
IF errorlevel 0 (echo Success. The OU has been created) GOTO :success
IF errorlevel 1 (echo Fail. The OU has NOT been created) GOTO :fail
:success
:fail
the error_ou.log file is generated before this part of the script from another command, it's always generated and always has the text time im doing a /find for. What am I doing wrong?
try this simple edit:
find /i "The OU has been created" error_ou.log
IF errorlevel 1 (echo Fail. The OU has NOT been created & GOTO :fail)
IF errorlevel 0 (echo Success. The OU has been created & GOTO :success)
:success
:fail
if errorlevel 1 (
echo failure
goto failure
) else (
echo success
goto success
)
Or, more similar to your code
if errorlevel 1 ( echo failure & goto failure )
echo success & goto success
There are two problems with your code.
The fist is causing the error you see: you forget to include the else
keyword and/or the concatenation of the two commands in the if
.
The second is a logic error. if errorlevel n
will be true for any errorlevel value equal or greater than n
, so if your first test is if errorlevel 0
, it will "always" be true. Check for errorlevel must be done from higher to lower values.
That way, in the second sample code, the if errorlevel 0
is omited, the previous if errorlevel 1
will handle any error from the find
command, leaving only the case of errorlevel 0
.
Wrong syntax. Use: IF something GOTO somewhere
But you can't use: IF something Do something and then GOTO somewhere
Try:
IF errorlevel 0 GOTO success
IF errorlevel 1 GOTO fail
:success
Echo Success: The OU has been created
GOTO end
:fail
Echo Fail
GOTO end
:end
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.