7

I'm writing a batch file to be executed from a pre-build event in Visual Studio.

How can I make it output errors, warnings and messages to the Visual Studio Error List?

It's very hard to search for this as most things that come up are how to fix errors, not throw them!

dav_i
  • 27,509
  • 17
  • 104
  • 136

1 Answers1

7

The output needs a special format:

<Filename> (<LineNumber>): Warning: <ErrorMessage>

Instead of Warning you could also use Error
Also the spaces are important!

You could create it like this one

echo %~f0 (!lineNo!^): Warning: Invalid target for production

And to give a hint for the error position you should add a more or less accurate line number.

if /i "!TargetPath:~-3!"=="DLL" (
    set "targetValid=1"
) ELSE (
    call :GetLineNumber lineNo +1 {3D967145-10B6-44A0-96EF-91B6C6E2DD0E}
    echo %~f0 (!lineNo!^): Warning: Invalid target '!TargetPath:~-3!' for production
)
....

:GetLineNumber returnVar add uniqueGUID
:::
:::
setlocal EnableDelayedExpansion
set "GetLineNumber.lineNo=0"
set /a "GetLineNumber.Add=%~2"
set "GetLineNumber.unique=%~3"

for /F "delims=:" %%L in ('findstr /n "!GetLineNumber.unique!" "%~f0"') do (
    set /a "GetLineNumber.lineNo=%%L"
)

(
endlocal
set /a "%~1=%GetLineNumber.lineNo%" + %GetLineNumber.Add%
)
exit /b
jeb
  • 78,592
  • 17
  • 171
  • 225
  • Nice! I managed to do `echo %~f0: Warning: Hello` and it was happy with just omitting the line number. Could you provide a link to documentation for this feature? – dav_i Apr 22 '15 at 13:50
  • Probably somewhere at msdn. But this code snipped comes directly from one of my batch files – jeb Apr 22 '15 at 14:03
  • 2
    Any idea how to output text with a severity of "message"? None of `Message`, `Info`, or `Information` works. – dlf Dec 13 '17 at 20:17
  • 2
    @dlf It's not possible this way. It seems to be necessary to write add ins or other overcomplicated stuff – jeb Dec 14 '17 at 08:08
  • See [MSBuild / Visual Studio aware error messages and message formats](https://blogs.msdn.microsoft.com/msbuild/2006/11/02/msbuild-visual-studio-aware-error-messages-and-message-formats/). It appears that "message" is not supported. – jsuddsjr Mar 05 '19 at 14:44
  • Do you know how to create a multi-line error message? When I try to print an error message that contains a newline, only the first line appears in the message. – inejwstine May 02 '19 at 18:14
  • @inejwstine I suppose, it's not possible, as Visual Studio parse single lines, therefore it can't detect a multi line error message. But you can create two error messages in that case – jeb May 03 '19 at 05:48
  • @jeb Yeah, and I've noticed that when Visual Studio outputs multiple error messages that have the same "signature" (file, line number, etc.) it merges them into a single multi-line message. But I haven't been able to figure out how they do it, because mine always just appear separately. Ah well. It still works. – inejwstine May 06 '19 at 15:29