基于.NET的MSBuild常用命令记录。
前言
Microsoft生成引擎是一个用于生成应用程序的平台。此引擎(也称为 MSBuild)为项目文件提供了一个XML架构,用于控制生成平台处理和生成软件的方式。Visual Studio会使用MSBuild,但MSBuild不依赖于Visual Studio。通过在项目或解决方案文件中调用msbuild.exe或dotnet build,可以在未安装Visual Studio的环境中安排和生成产品。
环境设置
以VS 2022为例,MSBuild可执行文件路径为C:\Program Files\Microsoft Visual Studio\2022\Community\MSBuild\Current\Bin
项目配置文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
<Target Name="PostBuild" AfterTargets="PostBuildEvent"> <Exec Command="if '$(IS_Integrated)' == 'true' (
 xcopy $(TargetPath) $(SolutionDir)..\Outputs\ /R /Y
 xcopy $(TargetDir)$(TargetName).dll $(SolutionDir)..\Outputs\ /R /Y
)" /> </Target>
<Target Name="CopyDirectory" AfterTargets="Build"> <PropertyGroup> <CopyCommand Condition="'$(OS)' == 'Windows_NT'">xcopy "$(SolutionDir)..\Outputs\*.dll" "$(ProjectDir)bin\$(Configuration)\netcoreapp3.1\" /E /D /I /Y </CopyCommand> <CopyCommand Condition="'$(OS)' != 'Windows_NT'">cp -r "$(SolutionDir)..\Outputs\*.dll" "$(ProjectDir)bin\$(Configuration)\netcoreapp3.1\" </CopyCommand> </PropertyGroup> <Exec Command="$(CopyCommand)" /> </Target>
<Target Name="CreateFolderIfNotExists" AfterTargets="Build"> <PropertyGroup> <uploadPath>$(ProjectDir)bin\$(Configuration)\upload</uploadPath> </PropertyGroup> <PropertyGroup> <CreateCommand Condition="'$(OS)' == 'Windows_NT'">if not exist "$(uploadPath)" md "$(uploadPath)"</CreateCommand> <CreateCommand Condition="'$(OS)'!= 'Windows_NT'">if [! -d "$(uploadPath)" ]; then mkdir -p "$(uploadPath)"; fi</CreateCommand> </PropertyGroup> <Exec Command="$(CreateCommand)" /> </Target>
|
命令行构建
对于单个dotnet项目,可使用以下命令构建
1 2 3 4
| # 项目文件携带环境变量的情况 MSBuild [project file] /p:PropertyName=Value # 举例 MSBuild test.csproj /p:IS_Integrated = true
|
批处理构建
对于模块较多的dotnet项目,可使用批处理脚本批量构建,并跟踪构建情况
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| @echo off set totalCount=14 set failCount=0 set failList="" chcp 65001
cd your/test.sln/path echo 正在构建test模块[进度 1/%totalCount%]... dotnet build test.sln > nul 2>&1 if %errorlevel% neq 0 ( echo test模块构建失败 set /a failCount=failCount + 1 set failList="%failList% test" ) else ( echo test模块已构建成功! )
set /a successCount=%totalCount% - %failCount% set /p DUMMY=构建成功%successCount%个,失败%failCount%个,失败的模块有[%failList%],请尝试手动构建,按回车键继续...
|
参考文档
用于MSBuild命令和属性的常用宏
MSBuild 属性说明
xcopy命令参数说明