windows 如何从批处理文件中的函数返回值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11419046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 09:40:49  来源:igfitidea点击:

How do I return a value from a function in a batch file?

windowsbatch-file

提问by AnthonyM

I have the following batch file

我有以下批处理文件

@echo off
setlocal EnableDelayedExpansion
for /f "delims==" %%J in (File_List.txt) do (
call :setDate %%J MYD
echo/Date is: %MYD%
)
endlocal &goto :eof

:setDate
SETLOCAL ENABLEEXTENSIONS
echo %1
echo %~2
set NAME=%1
set NAME=%NAME:~-11%
echo %NAME%
echo %~2
endlocal&set %2=%NAME%&goto :eof

but with File_List.txt containing file2012-05.csv

但 File_List.txt 包含 file2012-05.csv

I get

我得到

file2012-05.csv
MYD
2012-05.csv
MYD
Date is:

How do I actually get the function setDate to return the value I want?

我如何真正让函数 setDate 返回我想要的值?

回答by Elwood

As I don't understand from your script what you want to achieve, I reply (for completeness) to the original subject: returning a value from a function.

由于我从你的脚本中不明白你想要实现什么,我回复(为了完整性)原始主题:从函数返回一个值。

Here is how I do it:

这是我如何做到的:

@echo off

set myvar=
echo %myvar%
call :myfunction myvar
echo %myvar%
goto :eof

:myfunction
set %1=filled
goto :eof

Result is:

结果是:

empty 
filled

回答by Eitan T

The batch interpreter evaluates %MYD%at parse time, and at that time it's empty. That's why you have Delayed Expansion. Change this line:

批处理解释器%MYD%在解析时进行评估,当时它是空的。这就是为什么你有延迟扩展。改变这一行:

echo/Date is: %MYD%

to this:

对此:

echo/Date is: !MYD!

and it will work like you want, because then it tells the interpreter to evaluate MYDat run-time.

它会像你想要的那样工作,因为它会告诉解释器MYD在运行时进行评估。