批处理文件变量范围问题 [英] Batch file variable scope issue
问题描述
在尝试创建"dos"(Windows 7命令行)批处理文件时,我遇到了一个奇怪的变量范围问题,该文件执行一些字符串操作以创建新的文件路径.在下面的示例中,谁能看到为什么OUTPUT_FILENAME变量始终总是为空的原因?
I'm having a strange variable scope issue when trying to create a 'dos' (windows 7 command line) batch file which performs a bit of string manipulation to create new file paths. Can anyone see why the OUTPUT_FILENAME variable always ends up being null in the example below?
echo Enter the Data Input, S (Site) or U (User)
set /p DATA_TYPE=
echo.
echo Enter the Input File Name
set /p INPUT_FILENAME=
echo.
IF /I %DATA_TYPE%==u (
set OUTPUT_FILENAME=%INPUT_FILENAME:\users\=\Users\Outputs\%
set OUTPUT_FILENAME=%OUTPUT_FILENAME:xls=txt%
echo Output:
echo %OUTPUT_FILENAME%
)
IF /I %DATA_TYPE%==s (
set OUTPUT_FILENAME=%INPUT_FILENAME:\sites\=\Sites\Outputs\%
set OUTPUT_FILENAME=%OUTPUT_FILENAME:xls=txt%
echo Outputs:
echo %OUTPUT_FILENAME%
)
在此先感谢您的帮助,这真让我发疯!
Thanks in advance for any assistance, this is driving me nuts!
推荐答案
您需要启用延迟的扩展:
You need to enable the delayed expansion:
setlocal EnableDelayedExpansion
echo Enter the Data Input, S (Site) or U (User)
set /p DATA_TYPE=
echo.
echo Enter the Input File Name
set /p INPUT_FILENAME=
echo.
SET OUTPUT_FILENAME=Empty
IF /I %DATA_TYPE%==u (
set OUTPUT_FILENAME=!INPUT_FILENAME:\users\=\Users\Outputs\!
set OUTPUT_FILENAME=!OUTPUT_FILENAME:xls=txt!
echo Output:
echo !OUTPUT_FILENAME!
)
IF /I %DATA_TYPE%==s (
set OUTPUT_FILENAME=!INPUT_FILENAME:\sites\=\Sites\Outputs\!
set OUTPUT_FILENAME=!OUTPUT_FILENAME:xls=txt!
echo Outputs:
echo !OUTPUT_FILENAME!
)
作为SET
命令状态的帮助:
延迟的环境变量扩展对于避免当前扩展的局限性很有用,当前扩展的局限性是在读取一行文本时而不是在执行文本行时发生的.
Delayed environment variable expansion is useful for getting around the limitations of the current expansion which happens when a line of text is read, not when it is executed.
因此,您需要使用延迟扩展来确保INPUT_FILENAME
OUTPUT_FILENAME
的值在执行时被扩展.
So, you need to use the delayed expansion to make sure that INPUT_FILENAME
OUTPUT_FILENAME
's value are expanded at execution time.
这篇关于批处理文件变量范围问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!