批处理文件从函数调用返回值返回空白 - 拆分 csv 字符串并返回部分

问题描述 投票:0回答:1

为什么我的服务器和数据库变量的批处理文件代码中没有返回结果?

批号:

cls
@echo off
call :split2 "MyServer,MyDatabase" server database

echo server=%server%, database=%database%
goto End
:split2
setlocal enabledelayedexpansion
set x=%~1
echo x=%x%
set /a i=0
for %%b in ("%x:,=" "%") do (
    set array[!i!]=%%~b
    set /a i+=1
)
endlocal
setlocal enableextensions
set %2=%array[0]%
echo server=%2
set %3=%array[1]%
echo database=%3
endlocal
goto :eof
:End

结果:

x=MyServer,MyDatabase
server=server
database=database
server= , database=

不应该为空,我已经尝试了各种 setlocal 选项似乎没有任何效果。

batch-file
1个回答
0
投票

考虑这个脚本的精炼版本。

@echo off
call :split2 "MyServer,MyDatabase" server database

echo server=%server%, database=%database%
exit /b

:split2
setlocal enabledelayedexpansion
set x=%~1
set /a i=0
for %%b in ("%x:,=" "%") do (
    set array[!i!]=%%~b
    set /a i+=1
)
endlocal & (set "%2=%array[0]%") & (set "%3=%array[1]%")
exit /b

除了删除所有调试代码之外,主要区别在于

endlocal
在您设置(输出)变量的同时进行评估和解析。

endlocal & (set "%2=%array[0]%") & (set "%3=%array[1]%")
当您从

setlocal 子程序返回时,

endlocal
/
split2
内部
设置变量将无效。你必须在外面进行设置。

可能还有其他方法可以完成它,但在本例中,它是完成的,因为变量替换是在行parsed时进行的,但赋值发生在解析完成并且

endlocal
已执行之后。

© www.soinside.com 2019 - 2024. All rights reserved.