I have a C# solution in Visual Studio 2017. I also have a batch script called foobar.bat that contains the following code:
echo foobar : error 1: This is a test error.
My goal is to get only the test error message above to appear in Visual Studio's Error List when I build a particular project and for the build to stop when it appears. So I put [path to script]\foobar.bat in the project's post-build event command line and then build. Now I'm getting two error messages in the Visual Studio Error List:
The command "[path to script]\foobar.bat" exited with code -1.This is a test error.
In this case, seeing that first error message that just prints out the contents of my post-build event isn't helpful. I want to suppress this initial error so that only my custom error messages show up in the Error List (or at least change it to say something more useful).
Here's what I've tried:
- Adding
2>nulto the end of my batch script has no effect. - Adding
1>nulto the end of my batch script suppresses both errors, which isn't what I want. - Adding
&set errorlevel=0to the end of my batch script has no effect. - Adding the line
exit 0to the end of my batch script has no effect. - Adding the following to the end of my .csproj file (per this article) suppresses the first error, but makes it so the build no longer fails:
<Target
Name="PostBuildEvent"
Condition="'$(PostBuildEvent)'!=''"
DependsOnTargets="$(PostBuildEventDependsOn)">
<Exec WorkingDirectory="$(OutDir)" Command="$(PostBuildEvent)" IgnoreExitCode="true" />
</Target>
The last option almost gets me what I want. However, in spite of there being an error message, the Error List doesn't pop up and the build does not fail. It appears as though anything that would cause the initial error message to not appear will also cause the build to no longer fail. Is that the case? Or is there some way I can get the build to fail without showing that initial error message?
What you can do is use an
execand anerrortask together.You need to edit the .csproj file and add these tasks after your the
Target PostBuildEventfrom your last bullet point above.This solution works by getting the
ExitCodeandOutputof your exec task and using them to trigger the error task which will then stop the build and log the message.The
Exectask needs three parameters:IgnoreStandardErrorWarningFormatandIgnoreExitCodeprevent the error from being logged at this stepConsoleToMsBuildparameter is required to get the output (spelledConsoleToMSBuildin VS 2017).So the tasks look like this:
And edit the file
foobar.bat:The important part is the
exitthat will set the code we want to use afterwards.You can have more than one
Errortask do to more conditional logging or just use the output as is.