Difference in Delayed expansion of ERRORLEVEL on c

2020-03-24 11:04发布

cmd /V:ON /c dir c:\<some non existing directory> & echo %ERRORLEVEL%     
Volume in drive C is PC COE  Volume Serial Number is 9C37-D0B7

 Directory of c:\

File Not Found 
0

Lets run the same command using ! to expand the ERRORLEVEL (delayed expansion is enabled)

cmd /V:ON /c dir c:\ERt & echo !ERRORLEVEL!
 Volume in drive C is PC COE
 Volume Serial Number is 9C37-D0B7

 Directory of c:\

File Not Found
!ERRORLEVEL!

It prints !ERRORLEVEL!.

This does work fine when I run the command using a WMI win32_process create command and proper error is returned using the !ERRORLEVEL! variable

What difference it makes when executing in a cmd prompt and executing using WMI win32_process.?

1条回答
老娘就宠你
2楼-- · 2020-03-24 11:32

By using

cmd /V:ON /c dir c:\ERt & echo !ERRORLEVEL!

the new command process started with cmd /V:ON executes just the command dir c:\ERt and then closes and the second command echo !ERRORLEVEL! is executed by current command process on which delayed expansion is not enabled.

The command line

cmd /V:ON /c "dir c:\ERt & echo !ERRORLEVEL!"

must be used to run dir c:\ERt AND echo !ERRORLEVEL! in new command process before exiting this command process.

The double quotes around entire command line to execute in new command process makes the difference.

Without the double quotes around command line to execute in new command process the current command process interprets the line with the two commands as when typing

cmd /V:ON /c dir c:\ERt
echo !ERRORLEVEL!

Also possible would be

cmd /V:ON /c dir c:\ERt ^& echo !ERRORLEVEL!

Now & operator is escaped for current command process being interpreted as literal character and therefore the entire line is executed with caret character ^ removed by the new command process.

查看更多
登录 后发表回答