在PowerShell脚本中捕获MSBuild.exe输出

3
我正在使用PowerShell为一个项目创建一些新的构建脚本,并希望在调用MSBuild时捕获其输出并将其保存到文本文件中。我已经尝试了几种不同的方法,但都没有成功--这是我最后尝试的方法(Write-Buildlog只处理将输出写入日志):

Start-Process $msBuildExecutable $buildArgs -Wait | Write-Buildlog

尽管MSBuild运行良好,但根本没有捕获任何输出。如果您有任何提示,将不胜感激,因为我已经搜索了一些内容,但迄今为止没有找到任何有用的信息,这令人惊讶 :)
谢谢!
5个回答

3
如果你想将msbuild的输出导入到一个日志记录或处理cmdlet中,那么你不应该用Start-Process启动它,而是应该正常执行它。
PS> msbuild.exe $flag1 $flag2 $thingToBuild | Write-Buildlog

你可能需要将stderr也重定向以捕获更多的输出。在这种情况下,你需要添加2>&1

PS> msbuild.exe $flag1 $flag2 $thingToBuild  2>&1 | Write-Buildlog

Start-Process将在任何powershell环境或主机外启动您的进程,因此获取输出并发送到cmdlets变得更加困难。如果您想在powershell中处理可执行文件输出,则最好始终保持在powershell环境中。


嗨,这个好像也不行:$msBuildExecutable + $buildArgs 2>&1 | Write-BuildLog看起来甚至没有运行MSBuild? - DashRantic
更多细节--我想要运行一个特定版本的MSBuild,因此我将它存储在一个变量中。但是,似乎我不能按照你所提出的方式运行它,这就是我一开始使用Start-Process的原因--那么,如果不使用Start-Process,我还能用另外一种方法来实现吗? - DashRantic
还尝试了以下命令:& $msBuildExecutable $buildArgs 2>&1 | Write-BuildLog,但仍然没有任何输出。 - DashRantic
如果您的参数在一个数组中,您需要使用“splatting”将它们传递给一个期望一次一个地接收它们的可执行文件。PS> & $pathToMsBuild @buildArgs - latkin
它们不在一个数组中,只是一个字符串。 - DashRantic
2
无论您如何构造字符串,都请使用相同的输入来构造数组。或者,如果只有几个参数,请逐个传递它们,例如 PS> & $msbuildPath $arg1 $arg2 ... - latkin

2
Start-Process CmdLet 中,你有一个 -RedirectStandardOutput 参数;你测试过它了吗?
Start-Process -FilePath "C:\Windows\system32\ping.exe" -ArgumentList "MyMachine" -RedirectStandardOutput "c:\temp\p.txt" -NoNewWindow

你可以使用-RedirectStandardError来重定向错误信息。

谢谢!但我想将输出发送到我的Write-Buildlog cmdlet,这似乎-RedirectStandardError做不到? - DashRantic

2

你所需要的是:

& msbuild.exe .\yourproj.sln |Out-Host

甚至可以这样: & msbuild.exe .\yourproj.sln |Out-File c:\log.txt
如果你想将结果写入文件中。

1

如果您以这种方式运行输出,您可以随心所欲地处理它:

$MSBuild = [string](MSBuild.exe -argument1 -argument2 -andSoOn)

假设你想要将输出写入文件中。

$MSBuild = [string](MSBuild.exe -argument1 -argument2 -andSoOn) | Out-File C:\text.txt

或者这样写...

$MSBuild = [string](MSBuild.exe -argument1 -argument2 -andSoOn) 2>&1 >> C:\text.txt

注意: 2个“>>”表示追加,1个“>”表示覆盖先前添加的行。
或者,如果你只想从一组输出中获取一个单词,比如“true”。
$MSBuild = [string](MSBuild.exe -argument1 -argument2 -andSoOn)
if($MSBuid -match "true") 
{
    Write-Host "Whatever you want to say about what's true"
}

如果您想在控制台中看到所有内容,可以这样做。
$MSBuild = [string](MSBuild.exe -argument1 -argument2 -andSoOn) | Out-Host

或者...

$MSBuild = [string](MSBuild.exe -argument1 -argument2 -andSoOn)
Write-Host $MSBuild

0

我认为,你应该阅读有关 MsBuild 命令行中的日志记录选项的内容: http://msdn.microsoft.com/en-us/library/ms164311.aspx

使用 Msbuild /Logger 命令,您可以获得很好的输出日志选项。您可以在 Powershell 脚本中使用此参数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接