0

I'm running this simple command from command prompt and from a batch file. Although both "worked" in that the file is copied to the destination but the return code is always 1 when run from batch, and 0 from command prompt.

 copy /Y d:\my.zip C:\my\target\

I can't figure out where it was wrong except that I can see the return code when I

@echo on

Any tip is appreciated.

UPDATE

I digged further and noticed that I execute the command inside a if NOT %errorlevel% == 0 () block, once I moved it out then it runs ok. I've already setlocal enabledelayedexpansion and setlocal enableextensions, so I thought I should be ok doing stuff inside the if block, but turns out that it was a bad idea. Could you please explain what I did wrong initially?

Old code


setlocal enabledelayedexpansion
setlocal enableextensions

where mycmd
if NOT %errorlevel% == 0 (
   copy /Y d:\my.zip C:\my\target\
   if NOT %errorlevel% == 0 (
      echo Failed to copy
      goto :fail
   )
   start /wait cmd /c "tar -xvf c:\my\target\my.zip -C c:\my\target\"
   if NOT %errorlevel% == 0 (
      echo Failed to unzip
      goto :fail
   )
   setx PATH "%PATH%;c:\my\target"
   if NOT %errorlevel% == 0 (
      echo Failed to update user path
      goto :fail
   )
)

All these commands inside the top-level if-block fail. I thought the delayed expansion would work with the initial setlocal enabledelayedexpansion, but it turns out to be not the case.

Where was I wrong?

kakyo
  • 8,886
  • 12
  • 62
  • 119
  • 4
    @kakyo, inside a block with delayed expansion enabled, that would have needed to be `If Not !ErrorLevel! == 0`, or `If !ErrorLevel! Neq 0`. Athough inside a block you didn't need delayed expansion, had you used `If Not ErrorLevel 0`. Also if you open a Command Prompt window, type `where /?` and press the `[ENTER]` key, you should see the usahe information for the `where.exe` utility. Within that content you should note that it has a `/Q` option, which records the errorlevel, when checking for the existence of a file named `mycmd`. – Compo Jun 21 '21 at 10:09
  • @Compo AHHHHH. You are totally right! – kakyo Jun 21 '21 at 10:10
  • 4
    Also do not use `start` with or without `/wait` for running the `tar.exe` utility, just remove them, `%SystemRoot%\System32\tar.exe -xvf C:\my\target\my.zip -C C:\my\target`. And more importantly never use `setx` with `PATH`, by doing so, you've probably now corrupted your PATH environment variable, by including all of the content of your System PATH within the content of your User PATH. PATH is not like standard environment variables, it contains both environments in one, so you've added the content of System PATH, the content of User PATH, and `C:\my\target`, to your User PATH. – Compo Jun 21 '21 at 10:20

0 Answers0