Can't get errorlevel from failed MOVE command in batch script - batch-file

I'm pretty new to this forum so i first want to thank you for providing me with solutions even before i became a member :).
So I have this code:
for %%a in ("%PBpath%") do (
move "network location 1 files" "network location 2" >NUL
if ERRORLEVEL 0 (echo Diagram %%~na.pdf was successfuly archived) else ( echo Diagram %%~na.pdf was not archived )
ECHO.%errorlevel%
)
The problem is that I can't get the errorlevel different than 0. Even when the files that are to be copied are missing from location, i still get the successfuly archived message echoed. I searched the forum for similar questions, but i couldn't make it work for some reason.
Is there something different between the copy and the ping command (the ping command returns the correct exit code in the errorlevel), because i can't get it with either copy or move...
Thanks!
Andrew

The strange thing about the IF ERRORLEVEL statement is that it doesn't act like you expect- it returns TRUE if the errorlevel is equal to OR GREATER THAN the number specified.
A failure in MOVE sets errorlevel to 1 (I just checked) which is greater than 0. Therefore the first clause in the IF statement will always be used. The easiest way to fix your script is to reverse the conditions in the IF statement:
if ERRORLEVEL 1 (echo file was not archived) else (echo file was successfully archived)

Just use %ERRORLEVEL% variable instead of ERRORLEVEL function

If one wants to use the ERRORLEVEL function, Superbob's answer address' this (though I would recommend the form if NOT ERRORLEVEL 1 (echo file was successfully archived) else (echo file was not archived) instead).
But if one wants to use the %ERRORLEVEL% variable method instead, Delayed Expansion needs to be turned on. The OP's code above, with the recommended changes, is below:
setlocal enabledelayedexpansion
for %%a in ("%PBpath%") do (
move "network location 1 files" "network location 2" >NUL
if !ERRORLEVEL! equ 0 (
echo Diagram %%~na.pdf was successfully archived
) else (
echo Diagram %%~na.pdf was not archived)
)

Related

ERRORLEVEL of a FINDSTR command always returning 0

I have to remove an entry in the hosts file on some devices. The FINDSTR command is working, but always returning errorlevel 0.
I know that by default, the %errorlevel% is always 0.
So if the previous command is not setting the error code it will always return 0.
I basically need to find a string in the hosts file, if it exists it should save a new hosts file without the line containing the string.
This is what I do:
set HOSTSFILE=%WINDIR%\system32\drivers\etc\hosts
set TEMP_HOSTS=%TEMP%\%RANDOM%__hosts
FINDSTR /V /I /C:"string to search for" "%HOSTSFILE%" > "%TEMP_HOSTS%"
IF %ERRORLEVEL% EQU 0 COPY /b/v/y "%TEMP_HOSTS%" "%HOSTSFILE%"
This basically works. However, the above code will always return errorlevel 0 and thus always copy over the hosts file, even if the string is not present in the file.
I know it doesn't really matter, but I'm curious as to why the errorlevel is not working here?
The errorlevel should be set by the previous command, which in this case is the FINDSTR.
I've also tried with the FIND command and with !errorlevel! instead of %errorlevel%.

How to search a text file in batch for a specific symbol and alter the script depending on the result

I need to create a command that allows me to insert a check of a text file for a very specific symbol (’) and I am having trouble. It is a single quotation mark and it occasionally is found on some folders that need to be zipped and when my batch zipper encounters the folder with the symbol in it's name, it just starts having a lot of problems and creates weird files. I am not going into a lot of detail, but I just need a way to (in plain terms) check if a text file contains the symbol (’) and if it does, send the script to an error line (just something to indicate the symbol was found, like "echo error found"). And if not, then just send it to the rest of the script...
Like FINDSTR "’" dirlist.txt
if found goto err else goto resume
I know that is very incorrect but you get the idea.
Here is what I have so far and I still have made no progress getting it to work:
findstr /i /c:"’" C:\ACFZ\FORZIP\dirlist.txt >2
if %errorlevel% EQU 0 (goto LABEL0) else (goto LABEL1)
:LABEL0
msg %username& "An invalid symbol has been found. Remove any single quotation marks (’) from the folder names and try again. If unsure, simply remove anything that looks like an apostrophe."
pause
goto ERROR
:LABEL1
echo No errors found, continuing
pause
goto ZIPSTART
:ERROR
echo an error was found, exiting...
pause
goto EXIT
It always ends up saying no errors, even though the file has the symbol in it.
Here is the text file I need to search (dirlist)
2082708 Amboy Bank
2082712 Cavender’s
2082736 Elizabeth Board of Education
2082763 Tri-Valley Developmental Services LLC
2082773 Vector Management
OK, so I finally got it working right... Thanks to Harvey, I used the method of outputting any results to a separate file, and then checking that file for contents. Which actually works great, because if it finds an issue, it will show you the full name of the problem folder(s) so you can easily fix it.
Here is the snippet of the working part:
findstr "'" C:\ACFZ\FORZIP\dirlist.txt > error.txt
findstr "." error.txt >nul
IF %ERRORLEVEL% EQU 0 GOTO POPUP
IF %ERRORLEVEL% EQU 1 GOTO ALLCLEAR
and here it is with a bit more detail:
CD C:\ACFZ\FORZIP
DIR /AD /B /ON >dirlist.txt
Echo Checking for errors in folder names...
ping -n 3 localhost >nul
REM that is not an apostrophe!
findstr "'" C:\ACFZ\FORZIP\dirlist.txt > error.txt
findstr "." error.txt >nul
IF %ERRORLEVEL% EQU 0 GOTO POPUP
IF %ERRORLEVEL% EQU 1 GOTO ALLCLEAR
REM Errorlevel 0= Something found, 1= nothing found
:POPUP
color cf
msg %username% "An invalid symbol has been found. Remove any single quotation marks (’) from the folder names and try again. If unsure, simply remove anything that looks like an apostrophe."
goto ERROR
:ALLCLEAR
echo No errors found, continuing...
ping -n 3 localhost >nul
ping -n 3 localhost >nul
goto ZIPSTART
:ERROR
echo An error was found in the following folder name(s) below:^
findstr "." error.txt
echo.
Echo Remove any symbols from the above folder name(s)
echo within your completed folder and try again.
Echo This program will now exit.
pause
goto EXIT
:ZIPSTART
REM Zip contents of each directory
for /f "tokens=*" %%a in (dirlist.txt) do (
CD "%%a"
wzzip "C:\ACFZ\ZIPPED\%%a.zip"
CD..
)
Glad I was able to fix this. I guess WinZip goes really crazy from that quotation mark. The reason I needed this was I wrote this batch script (there is more to it than what I have above, as this was the part I needed to work on) to automate the zipping and backup process at my work, so that the folders for the month's jobs are zipped up and then copied onto the server for archive. It was a pain to manually do it, so with this I can just do it all in one step.
Oh and yeah the errorlevel issue was I did not have it entered correctly. I did not space them over to the right.
Thanks to all who helped.
%error_level% indicates the status of the execution which always successful (0) unless you pass in wrong arguments (e.g. try run findstr without argument or with a wrong file name).
In your case, you need to examine the output (messages printed on the screen) of findstr. One approach is to rely on the fact that nothing is printed on the screen if findstr finds no string matched the search. For example:
set found=""
findstr "'" C:\ACFZ\FORZIP\dirlist.txt > findresult.txt
call:CheckEmptyFile findresult.txt found
if "%found%" EQU "FOUND" (
echo An invalid symbol has been found
) else (
echo No errors found, continuing
)
REM your execution goes here
REM Clean up
del findresult.txt
goto :eof
:CheckEmptyFile
if %~z1 == 0 (
set "%~2=NOTFOUND"
) else (
set "%~2=FOUND"
)
goto :eof
(Reference: Windows BAT : test if a specific file is empty)

CHOICE returning error

Problem
I have 2 folders (each contain one file), and I am trying to copy the files from one to the other. The CHOICE command I have written works properly; however, after an answer is chosen the program closes immediately (no matter what choice is selected). A line was displayed "1 was unexpected at this time" as it was closing.
My Code
ECHO. & CHOICE /C:123 /N /M "Copy? (1. Copy 2. Exit 3. No Choice)" & ECHO.
::assigns choice values for user
IF /i %errorlevel1% EQU 1 GOTO copy
IF /i %errorlevel2% EQU 2 GOTO end
IF /i %errorlevel3% EQU 3 GOTO no_choice
::based on selection, redirects to logic
:copy
ECHO.
ECHO.
ECHO You chose to COPY the files... Hit any key to START or ctrl-z to CANCEL.
PAUSE > NUL
SET src_folder=d:\batch
SET dst_folder=d:\newBatch
FOR /F "tokens=*" %%i in (batch.txt) DO (
xcopy /S/E/U "%src_folder%\%%i" "%dst_folder%")
GOTO end
::offers cancel; if continue, copies files from batch to newBatch
:end
EXIT
::ends program
:no_choice
ECHO No action has been performed...
PAUSE
EXIT
::print message; then ends program
Research
I have searched all over the web, as well as some of this site's posts, and it helped me construe what I currently have here. The most recent Stack Overflow post I reviewed over this topic was found here (Error: 1 was unexpected at this time). I implemented the "/i" fix that was mentioned in this post, but the individual asking the question was simply validating ECHO statements rather than CHOICE.
Question
I am confused as to where this error is occurring since there are no debugging features that I'm aware of in Batch programming, and the program closes immediately at the point of error. (is the CHOICE statement wrong, or is the subsequent logic causing this problem?)
Should I avoid the CHOICE method and handle this process similarly to the post I referenced? (is validating ECHO better than using CHOICE in this case?)
Thanks!
You made a mistake in the name of ERRORLEVEL variable.
IF %errorlevel% EQU 1 GOTO copy
IF %errorlevel% EQU 2 GOTO end
IF %errorlevel% EQU 3 GOTO no_choice
The /i option is not necessary in this case...

How can I display a description based on errorlevel value?

I'm writing a batch script to install an exe and a successful installation returns 0 and other codes mean different reasons.
I know I can print those error code(s) by echo %errorlevel%
Can I print the description related to the code instead? If so, how?
i.e. print 'successful' for code 0, etc.
Add below lines to print a message using error codes
if %errorlevel% equ 0 echo Successful
if %errorlevel% NEQ 0 echo Not Successful
Because errorlevel 0 indicates that return values of last executed command is successful,other return values have their own meaning
You can use || to act on failure, for simplicities sake this should do fine.
if %errorlevel% equ 0 echo Installed! || echo Install failed...
And && to activate on success.
del file.ext && echo File deleted.
The reason I don't provide a per errorlevel basis is that there can be up to 255 of them, something that would take an exceedingly high amount of time, and is further hindered by the tendency of programs not publically showing or ever documenting what each and every errorlevel means.
Something good to keep in mind is the difference between %errorlevel% and errorlevel. here

batch ERRORLEVEL always 0

I'm facing an issue when trying to implement the ERRORLEVEL on my batch script. Basically what I'm trying to do is: look for the .txt files in the directory and if found; .txt will get listed, if not found; message error will occur.
The thing is that this directory will not always contain a .txt, sometimes it will be empty and when that happens my code will not work. Only when there is a .txt in the directory I'm getting my conditions to work (ERRORLEVEL = 0), but if empty; none of my conditions will. Not even the ERRORLEVEL will be printed in the cmd screen (I should see it as ERRORLEVEL = 1).
This is my code:
for /r "C:\Texts" %%a in (*.txt) do (
echo %errorlevel%
IF ERRORLEVEL 0 (
echo %%a
echo "I found your Text!"
) ELSE (
echo "I couldn`t find your Text!" )
)
What exactly is wrong with my ERRORLEVEL implementation?
Errorlevel 0 is always true.
Use
if not errorlevel 1
But your code doesn't set the errorlevel.
In your code there is not any command that set the errorlevel. This value is set by all external .exe commands (like find or findstr), and by certain specific internal commands (like verify that set errorlevel=1 when its parameter is wrong, or ver that always set the errorlevel=0.
You may explicitly set this value in your code this way:
rem Set the errorlevel to 1
verify bad 2> NUL
for /r "C:\Texts" %%a in (*.txt) do (
echo %%a
rem Set the errorlevel to 0
ver > NUL
)
if not ERRORLEVEL 1 (
echo "I found your Text!"
) else (
echo "I couldn't find your Text!"
)
However, you may also get a similar result using a Batch variable instead of the errorlevel...

Resources