.net - 如何在不生成 msbuild.exe 进程的情况下从 Powershell 运行 MSBuild?

标签 .net powershell msbuild

我正在考虑通过直接点击 MSBuild 程序集(而不是查找 MSBuild 安装路径并将 msbuild.exe 作为子进程启动)从 Powershell 脚本运行 MSBuild。

有没有人做过这个?运行构建的最简单、最直接的方法是什么?您想指出的这两种技术有什么优点/缺点吗? (我对在与脚本的其余部分相同的进程/应用程序域中运行 msbuild 可能出现的任何问题特别感兴趣)。

目前我的想法是这样的:

[void][System.Reflection.Assembly]::Load('Microsoft.Build.Engine, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
[void][Microsoft.Build.BuildEngine.Engine]::GlobalEngine.BuildProjectFile("path/main.proj")

最佳答案

工作并产生输出的最简单的嵌入式构建调用是:

[void][System.Reflection.Assembly]::Load('Microsoft.Build.Engine, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
$engine = New-Object Microsoft.Build.BuildEngine.Engine
$engine.RegisterLogger((New-Object Microsoft.Build.BuildEngine.ConsoleLogger))
$engine.BuildProjectFile('fullPath\some.proj')

然而,事实证明直接在 Powershell (V1) 中嵌入 MSBuild 是有问题的:
'MSBUILD : warning MSB4056: The MSBuild engine must be called on
a single-threaded-apartment. Current threading model is "MTA".
Proceeding, but some tasks may not function correctly.'

为什么哦,为什么我们在 2009 年在托管环境中工作时还要缴纳 COM 税?

我的结论是在 Powershell (V1) 中嵌入 MSBuild 不是一个好主意。作为引用,我还包括了我最终使用的基于流程的方法:
[void][System.Reflection.Assembly]::Load('Microsoft.Build.Utilities.v3.5, Version=3.5.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a')
$msbuild = [Microsoft.Build.Utilities.ToolLocationHelper]::GetPathToDotNetFrameworkFile("msbuild.exe", "VersionLatest")
&$msbuild fullPath\some.proj

关于.net - 如何在不生成 msbuild.exe 进程的情况下从 Powershell 运行 MSBuild?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/472038/

相关文章:

c# - mySQL备份和恢复c#

powershell - 使用powershell将文件名中每个单词的首字母大写

powershell - 是否可以将字符串(特别是冒号)插入整数变量?

dependency-injection - IoC : ProjectReference with ReferenceOutputAssembly = false, 但仍然想要 nuget 包

c# - Visual Studio 2017 无法复制 dll,因为它正被 MSBuild.exe 进程使用

c# - 来自 StreamReader 的原始文件字节,魔数(Magic Number)检测

java - 构造函数中的虚函数,为什么语言不同?

c# - ExecuteReader等待操作超时错误

powershell - Power Shell:在内存中使用变量/字符串生成器的最有效方法是什么?

c# - 如何根据所选配置将项目构建为可移植或普通类库?