gpt4 book ai didi

batch-file - 批处理文件变量范围问题

转载 作者:行者123 更新时间:2023-12-04 01:55:51 25 4
gpt4 key购买 nike

在尝试创建一个“dos”(Windows 7 命令行)批处理文件时,我遇到了一个奇怪的变量范围问题,该批处理文件执行一些字符串操作以创建新的文件路径。谁能看出为什么在下面的示例中 OUTPUT_FILENAME 变量最终总是为空?

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%
)

在此先感谢您的任何帮助,这让我发疯了!

最佳答案

您需要启用延迟扩展:

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的值在执行时扩展。

关于batch-file - 批处理文件变量范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21387098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com