0

I was playing around in batch and I noticed that the script below doesn't return the same errorlevel for the same command.

I've had problems with the errorlevel variable before and I was wondering why this is happening

@echo off
cd C:\NotARealFolder & echo %errorlevel%

cd C:\NotARealFolder
echo %errorlevel%

pause
Azias
  • 37
  • 1
  • 8
  • 5
    Maybe [this](http://stackoverflow.com/a/26252288/2861476) could help – MC ND May 18 '17 at 07:21
  • @mc-nd I wasn't aware of that, thank you – Azias May 18 '17 at 07:28
  • `cd C:\NotARealFolder & echo %errorlevel%` with run both `cd` and `echo` commands at the same time, so you can you get the errorlevel of `cd` when it hasn't finished running? – phuclv May 18 '17 at 07:30
  • 6
    @LưuVĩnhPhúc, the `cd` command *is* finished before `echo` is executed; the problem is immediate variable expansion, because `%ErrorLevel%` is expanded when the entire line is parsed, so it returns the value present before the entire line is executed; switching to [delayed expansion](http://ss64.com/nt/delayedexpansion.html) solves the problem, because `!ErrorLevel!` expands the value at runtime, so you are going to receive the value returned by `cd` then... – aschipfl May 18 '17 at 09:03

0 Answers0