为什么在 TeamCity 构建中,后期构建步骤(xcopy)偶尔会以代码2退出?

我客户解决方案中的一些项目有一个生成后事件: xcopy生成输出到特定文件夹。这在本地构建时可以很好地工作。但是,在团队城市,我 偶尔得到

Xcopy [ ... ]以代码2退出

如果我使用常规 copy,它退出代码1。我希望这与文件锁有关,尽管所复制的特定文件不相同,因此可能只是锁定共享目标目录。我使用 /y不提示覆盖文件。

为什么这在 TeamCity 中会失败,而在本地却不会?

78402 次浏览

If you are using xcopy in a post build event use the /Y switch in addition to the /C.

/C           Continues copying even if errors occur.
/Y           Suppresses prompting to confirm you want to overwrite an existing file.

Even if you provide the /Y switch with xcopy, you'll still get an error when xcopy doesn't know if the thing you are copying is a file or a directory. This error will appear as "exited with code 2". When you run the same xcopy at a command prompt, you'll see that xcopy is asking for a response of file or directory.

To resolve this issue with an automated build, you can echo in a pre-defined response with a pipe.

To say the thing you are copying is a file, echo in F:

echo F|xcopy /y ...

To say the thing you are copying is a directory, echo in D:

echo D|xcopy /y ...

Sometimes the above can be resolved by simply using a copy command instead of xcopy:

copy /y ...

However, if there are non-existent directories leading up to the final file destination, then an "exited with code 1" will occur.

Remember: use the /C switch and xcopy with caution.

My fix for this issue was to go into the target bin folder, and ensure that the proper subfolder exists there. Once that subfolder was manually created, the build process completed successfully.

I fixed the error code 2 by adding a \ at the end of my path, without it, xcopy will think that it is a file instead of a folder.

Probably you using TeamCity with git. If yes, check that folders you want to copy are exists in git repository. Usually git aviod adding empty project folders to repository, so xcopy fails to find it and generates a error.

You can add some empty text file to empty folder, commit and see folder appears in repository.

copy fixed it for me. xcopy with /c /y did not work. I was getting an exit 4 so I went with xcopy, but turned out I needed quotes around ($TargetPath).

My script:

if $(ConfigurationName) == Debug copy "$(TargetPath)" "$(SolutionDir)\Folder\bin\Debug\$(TargetFileName)"