Windows CMD 脚本:为什么 SET 在括号内不起作用?

Windows CMD 脚本:为什么 SET 在括号内不起作用?

实际上我想将输出重定向到类似文件

@echo off
(
  set res=fail
  echo %res%
) > out.log

重定向本身工作正常...但为什么括号内的 %res% 是空的?

@echo off

setlocal EnableDelayedExpansion
rem This does not affect/help here

(
  setlocal EnableDelayedExpansion
  rem This does not affect/help here too

  set res=fail
  echo %res%  
  rem res is empty here
)
echo %res%    
rem res=fail here

答案1

这里有 2 个问题:

(1)您应该在批处理脚本中执行它,而不是在命令行中执行它。

(2) 应将EXCLAMATION !( not PERCENT %) 与 一起使用SETLOCAL ENABLEDELAYEDEXPANSION

这是一个工作案例,您可以将其放入 BT.BAT 中进行检查。

SETLOCAL ENABLEEXTENSIONS
IF ERRORLEVEL 1 ECHO UNABLE TO ENABLE EXTENSIONS

SETLOCAL ENABLEDELAYEDEXPANSION
IF ERRORLEVEL 1 ECHO UNABLE TO ENABLE DELAYED EXPANSION

SET res=UNfail
ECHO OFF

ECHO OUTSIDE 1 WITH PERCENT : %res%
ECHO OUTSIDE 1 WITH EXCLAMATION : !res!

(
  SETLOCAL ENABLEDELAYEDEXPANSION
  SETLOCAL ENABLEEXTENSIONS
  SET res=fail

  ECHO INSIDE 1 WITH PERCENT : %res%
  ECHO INSIDE 1 WITH EXCLAMATION : !res!
)

ECHO OUTSIDE 2 WITH PERCENT : %res%
ECHO OUTSIDE 2 WITH EXCLAMATION : !res!

(
  SETLOCAL ENABLEDELAYEDEXPANSION
  SETLOCAL ENABLEEXTENSIONS
  SET res=failUN

  ECHO INSIDE 2 WITH PERCENT : %res%
  ECHO INSIDE 2 WITH EXCLAMATION : !res!
)

ECHO OUTSIDE 3 WITH PERCENT : %res%
ECHO OUTSIDE 3 WITH EXCLAMATION : !res!

输出 :

OUTSIDE 1 WITH PERCENT : UNfail
OUTSIDE 1 WITH EXCLAMATION : UNfail
INSIDE 1 WITH PERCENT : UNfail
INSIDE 1 WITH EXCLAMATION : fail
OUTSIDE 2 WITH PERCENT : fail
OUTSIDE 2 WITH EXCLAMATION : fail
INSIDE 2 WITH PERCENT : fail
INSIDE 2 WITH EXCLAMATION : failUN
OUTSIDE 3 WITH PERCENT : failUN
OUTSIDE 3 WITH EXCLAMATION : failUN

相关内容