Output errors, warnings and messages from batch file in Visual Studio build event
Asked Answered
B

1

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!

Beware answered 22/4, 2015 at 13:30 Comment(0)
H
8

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
Hubing answered 22/4, 2015 at 13:46 Comment(8)
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?Beware
Probably somewhere at msdn. But this code snipped comes directly from one of my batch filesHubing
Any idea how to output text with a severity of "message"? None of Message, Info, or Information works.Stander
@Stander It's not possible this way. It seems to be necessary to write add ins or other overcomplicated stuffHubing
See MSBuild / Visual Studio aware error messages and message formats. It appears that "message" is not supported.Boatswain
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.Khabarovsk
@Khabarovsk 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 caseHubing
@Hubing 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.Khabarovsk

© 2022 - 2024 — McMap. All rights reserved.