我目前正在批量实施一个后期处理,经过一些修改后,一些代码片段再也无法工作了....
我想做什么:
@echo off & setlocal
ECHO %netUse% //For debugging!
IF NOT "%netUse%" == "" ( //Double checking if Variable is set
IF %netUse% EQU 1 (
IF %netUsePW% EQU 1 (
NET USE %netUseLetter% %netPath% %pw% /user:%netUser%
)
IF %netUsePW% EQU 0 (
NET USE %netUseLetter% %netPath%
)
)
)
当我运行该代码时,这是输出:
C:\Program Files (x86)\ID GmbH\PRODETTE\DAX\ISDN>ECHO 0
0 <--- That's right! It is set to ZERO via a "configuration" Batch
"1" kann syntaktisch an dieser Stelle nicht verarbeitet werden. <-- ???
C:\Program Files (x86)\ID GmbH\PRODETTE\DAX\ISDN> IF EQU 1 ( <-- Why isn't it comparing the variable?
为了完成者的缘故,我将所有这些变量加载到另一个批处理文件中,&#34; Settings.bat&#34; 我通过运行该文件 CALL:postCopySettings.bat
内容:
SET netUse=0
SET netUsePW=
SET netUseLetter=
SET netPath=
SET netUser=
SET pw=
SET configLoaded=1
(由于netUse为0,我不需要填充其他变量......对吗?)
TL:DR:批处理不起作用,但我不知道原因。
答案 0 :(得分:0)
IF NOT "%netUse%" == "" ( //Double checking if Variable is set
IF %netUse% EQU 1 (
IF %netUsePW% EQU 1 (
测试中没有意义&#34; netuse&#34;然后抱怨&#34; netusePW&#34;没有设定。
答案 1 :(得分:0)
问题是未设置变量netUsePW
。
当netUse
设置为0
时,netUsePW
,netUseLetter
,netUsePath
,pw
都为空,您的代码为.. :
@echo off & setlocal
ECHO %netUse%
IF NOT "%netUse%" == "" (
IF %netUse% EQU 1 (
IF %netUsePW% EQU 1 (
NET USE %netUseLetter% %netPath% %pw% /user:%netUser%
)
IF %netUsePW% EQU 0 (
NET USE %netUseLetter% %netPath%
)
)
)
...扩展为......:
@echo off & setlocal
ECHO 0
IF NOT "0" == "" (
IF 0 EQU 1 (
IF EQU 1 (
NET USE /user:0
)
IF EQU 0 (
NET USE
)
)
)
如您所见,有两个语法问题,导致错误:
IF EQU 1 IF EQU 0
虽然netUse
设置为0
,因此您希望IF %netUse% EQU 1
之后的语句不被执行,但它们仍然被解析,因为在任何命令之前解析整个代码块执行。
为了克服这个问题,有几种方法:
使用非空值预设变量:
@echo off & setlocal
ECHO %netUse%
IF "%netUse%" == "" (set "netUse=-1" & set "setUsePW=-1")
IF NOT "%netUse%" == "" (
IF %netUse% EQU 1 (
IF %netUsePW% EQU 1 (
NET USE %netUseLetter% %netPath% %pw% /user:%netUser%
)
IF %netUsePW% EQU 0 (
NET USE %netUseLetter% %netPath%
)
)
)
通过改变逻辑并使用{{1}}:
来避免代码块goto
通过将一些代码移动到子程序中并使用@echo off & setlocal
ECHO %netUse%
IF "%netUse%" == "" goto :SKIP
IF %netUse% NEQ 1 goto :SKIP
IF %netUsePW% EQU 1 (
NET USE %netUseLetter% %netPath% %pw% /user:%netUser%
)
IF %netUsePW% EQU 0 (
NET USE %netUseLetter% %netPath%
)
:SKIP
来调用它们来避免代码块:
call
启用并应用delayed expansion在执行期间而不是在解析时执行变量扩展:
@echo off & setlocal
ECHO %netUse%
IF NOT "%netUse%" == "" call :TEST "%netUse%" "%netUsePW%" "%netUseLetter%" "%netPath%" "%pw%"
exit /B
:TEST
IF %~1 EQU 1 call :TESTPW "%~1" "%~2" "%~3" "%~4" "%~5"
exit /B
:TESTPW
IF %~2 EQU 1 (
NET USE %~3 %~4 %~5 /user:%~1
)
IF %~2 EQU 0 (
NET USE %~3 %~4
)
exit /B