如何从命令行为 Visual Studio 创建一个简单的构建脚本?

How to create a Simple Build Script for Visual Studio from the Command Line?

我在多个目录中有很多 Visual Studio 项目解决方案(都带有扩展名 .sln),我想编写一个简单的批处理脚本来自动构建批处理文件中列出的所有解决方案。

我可以通过启动 Visual Studio Command Prompt 来手动构建解决方案(这只是一个执行了以下命令的命令行实例

"%comspec%" /k "C:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86

然后我通过调用构建项目:

devenv "path\to\solutionFile\projectSolution1.sln" /build Debug

这将构建项目(假设项目没有错误),我会为每个我想要构建的项目冲洗并重复。

但是 当我在名为 build.bat 的批处理文件中有以下内容时:

"%comspec%" /k "C:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86  
echo "Starting Build for all Projects with proposed changes" 
echo . 
devenv "path\to\solutionFile\projectSolution2.sln" /build Debug
devenv "another\path\to\solutionFile\projectSolution3.sln" /build Debug
devenv "yet\another\path\to\solutionFile\projectSolution4.sln" /build Debug
echo "All builds completed."
pause

批处理脚本只执行第一行,等我输入exit后再执行其他的。根据我对批处理文件所做的研究和所有 Whosebug 问题,我对此的理解是 cmd 实际上调用了另一个执行 vcvarsall.bat 的实例来设置构建环境。

这将不起作用,因为键入 exit 会杀死设置了 devenv 的实例,并且之后的命令无法执行,因为 devenv 不是可识别的命令(因为导出的路径将不复存在)

简而言之,如何在单个批处理文件中实现(将其余命令传递给定义了 devenv 的 cmd 实例)?我知道这不是调用构建的可靠方式(并且有很多工具可以执行此操作),但我只是希望有一个批处理脚本来自动执行单独调用这些项目的手动工作。

如果这已经在批处理脚本中,则此行:

"%comspec%" /k "C:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86  

可能应该只是 "C:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86

为什么? %comspec% 只是 cmd.exe 的环境变量快捷方式,所以如您所见,它启动了一个新的 cmd 实例,并指定了 /k 选项(如果您 运行 cmd /?Carries out the command specified by string but remains)。您不关心它是否剩余,您甚至不需要新的 cmd.exe,因为您已经 运行 正在处理您的批处理文件。

找到解决方案,正如 Jimmy 指出的那样,需要删除环境变量 %comspec%,因为它是 CMD.exe 的快捷方式。

但是,仅删除 "%comspec" /k 将导致 CMD 实例打开,然后在一秒钟后退出。我之前也尝试过 call 函数,该函数在与 %comspec%

一起使用时创建了一个单独的 CMD 实例

解决方法是在第一行前面加上call,去掉%comspec

这是让事情按预期工作的最终批处理文件。

@echo OFF 
call "C:\Program Files\Microsoft Visual Studio 10.0\VC\vcvarsall.bat" x86
echo "Starting Build for all Projects with proposed changes"
echo .  
devenv "path\to\solutionFile\projectSolution2.sln" /build Debug 
devenv "another\path\to\solutionFile\projectSolution3.sln" /build Debug 
devenv "yet\another\path\to\solutionFile\projectSolution4.sln" /build Debug 
echo . 
echo "All builds completed." 
pause

请注意,@echo OFF 告诉批处理脚本不要将命令(例如 call 命令)回显到终端中(但仍会显示错误和警告)