如何在Visual Studio 2017(C#)中抑制初始的构建后事件错误?

问题描述 投票:1回答:1

我在Visual Studio 2017中有一个C#解决方案。我还有一个名为foobar.bat的批处理脚本,它包含以下代码:

echo foobar : error 1: This is a test error.           

我的目标是在构建特定项目时将上面的测试错误消息仅显示在Visual Studio的错误列表中,并使构建在出现时停止。所以我将[path to script]\foobar.bat放在项目的post-build事件命令行中然后构建。现在我在Visual Studio错误列表中收到两条错误消息:

  1. The command "[path to script]\foobar.bat" exited with code -1.
  2. This is a test error.

在这种情况下,看到刚刚打印出构建后事件内容的第一条错误消息没有帮助。我想要抑制这个初始错误,以便只有我的自定义错误消息显示在错误列表中(或者至少更改它以说出更有用的内容)。

这是我尝试过的:

  • 2>nul添加到我的批处理脚本的末尾无效。
  • 1>nul添加到我的批处理脚本的末尾会抑制这两个错误,这不是我想要的。
  • &set errorlevel=0添加到我的批处理脚本的末尾无效。
  • 将行exit 0添加到我的批处理脚本的末尾无效。
  • 将以下内容添加到我的.csproj文件的末尾(每个this article)会抑制第一个错误,但会使构建不再失败:
<Target
    Name="PostBuildEvent"
    Condition="'$(PostBuildEvent)'!=''"
    DependsOnTargets="$(PostBuildEventDependsOn)">
    <Exec WorkingDirectory="$(OutDir)" Command="$(PostBuildEvent)" IgnoreExitCode="true" />
</Target>

最后一个选项几乎让我得到了我想要的东西。但是,尽管存在错误消息,但不会弹出错误列表,并且构建不会失败。看起来好像导致初始错误消息不出现的任何内容也会导致构建不再失败。是这样的吗?或者是否有某些方法可以让构建失败而不显示初始错误消息?

c# visual-studio visual-studio-2017 post-build-event build-events
1个回答
3
投票

你可以做的是一起使用execerror任务。

您需要编辑.csproj文件,并在上一个项目符号点的Target PostBuildEvent之后添加这些任务。

这个解决方案的工作原理是获取你的exec任务的ExitCodeOutput,并使用它们来触发错误任务,然后停止构建并记录消息。 Exec任务需要三个参数:

  • IgnoreStandardErrorWarningFormatIgnoreExitCode可防止在此步骤中记录错误
  • 获得输出需要ConsoleToMsBuild参数(VS 2017中拼写为ConsoleToMSBuild)。

所以任务看起来像这样:

  <Target Name="PostBuild" AfterTargets="PostBuildEvent">
    <Exec Command="$(PostBuildEvent)" IgnoreStandardErrorWarningFormat="true" IgnoreExitCode="true" ConsoleToMsBuild="true">
      <Output TaskParameter="ConsoleOutput" PropertyName="OutputMessage" />
      <Output TaskParameter="ExitCode" PropertyName="ExitCode" />
    </Exec>
    <Error Text="$(OutputMessage)" Condition="$(ExitCode) == 10" />
    <!-- <Error Text="(optional text) : $(OutputMessage)" Condition="$(ExitCode) == 11" />
    <Error Text="(optional text) : $(OutputMessage)" Condition="$(ExitCode) == 12" /> -->
  </Target>

并编辑文件foobar.bat

echo foobar : error 1: This is a test error.
exit /b 10 <-- /b parameter needed if used in a .bat file

重要的部分是exit,它将设置我们想要在之后使用的代码。

你可以有多个Error任务做更多的条件记录或只是按原样使用输出。

© www.soinside.com 2019 - 2024. All rights reserved.