TeamCity命令行Bat构建步骤环境参数传递异常排查
问题
使用TeamCity 2023.05.2(build 129341)版本,Unity项目的Unity构建步骤运行正常,但后续执行复制构建文件夹的.bat脚本时,提示源文件夹不存在。
Bat脚本内容
@echo off setlocal enabledelayedexpansion set "SourceFolder=%env.CHECKOUTDIR%\BTSCORE" set "DestinationFolder=C:\Test" echo SourceFolder is located at: %env.CHECKOUTDIR% :: Find the last subfolder with relevant files based on commit number and datetime for /f "tokens=*" %%d in ('dir /b /ad /o-n "%SourceFolder%\*"') do ( set "LastSubfolder=%%d" goto :FoundLast ) :FoundLast echo Last subfolder: !LastSubfolder! :: Construct source and target paths set "SourcePath=%SourceFolder%\!LastSubfolder!" set "TargetPath=%DestinationFolder%\!LastSubfolder!" if not exist "%SourcePath%" ( echo Source folder does not exist! exit /b 1 ) :: Create the target directory if it does not exist if not exist "%TargetPath%" ( mkdir "%TargetPath%" ) :: Copy the contents of the last subfolder to the target folder xcopy /s /e /i "%SourcePath%\*" "%TargetPath%" if errorlevel 1 ( echo Copy failed! ) else ( echo Copy succeeded! ) endlocal
执行日志
Starting: G:\BatFiles\CopyBuild.bat G:\TeamCity\BuildAgent\Work\f1099063e78e73d4 18:09:12 in directory: G:\BatFiles 18:09:12 SourceFolder is located at: 18:09:12 Das System kann die angegebene Datei nicht finden. 18:09:12 Last subfolder: 18:09:12 Source folder does not exist 18:09:12 Process exited with code 1 18:09:12 Process exited with code 1 (Step: Copy Files (Command Line)) 18:09:12 Step Copy Files (Command Line) failed
已尝试将变量设为TeamCity环境参数传入Bat文件,但问题仍未解决,询问遗漏的配置项。
解决方案
从日志可见%env.CHECKOUTDIR%未获取到有效值,结合TeamCity环境变量传递规则,排查以下几个关键配置点:
修正Bat脚本的变量引用格式
Windows批处理不识别env.前缀的变量写法,这是Linux/Shell脚本的引用方式。直接使用TeamCity内置变量的原生名称即可,修改脚本中相关行:set "SourceFolder=%CHECKOUTDIR%\BTSCORE" echo SourceFolder is located at: %CHECKOUTDIR%确认TeamCity参数的传递权限
- 若使用自定义参数而非内置
CHECKOUTDIR,需在参数配置页勾选**"Pass this parameter to build"和"Show this parameter in the build log"**,确保参数能传递到命令行步骤。 - 检查构建步骤的**"Run as"**配置,若切换到非代理默认用户执行,可能导致环境变量丢失,需保持使用代理默认用户。
- 若使用自定义参数而非内置
调整命令行步骤的工作目录
日志显示脚本在G:\BatFiles目录执行,而实际构建工作目录是G:\TeamCity\BuildAgent\Work\f1099063e78e73d4。可直接利用脚本启动时传入的工作目录参数(日志中已作为第一个参数传递),修改脚本:set "SourceFolder=%1\BTSCORE" echo SourceFolder is located at: %1或在命令行步骤的配置中,将工作目录设置为
%teamcity.build.workingDir%。验证环境变量的存在性
在命令行步骤中添加前置命令set CHECKOUTDIR,查看该变量是否被正确注入到执行环境。若输出为空,需检查TeamCity代理配置,确保代理服务有足够权限读取服务器下发的参数。
内容的提问来源于stack exchange,提问作者bts_slawa
相关产品推荐
相关产品推荐

