处理此问题的一种方法可能是让 MSBuild 将参数传递给批处理文件,以便它知道 MSBuild 正在调用它,而不是从命令提示符处调用它。例如,我创建了如下所示的示例文件 test.bat
ECHO OFF
IF (%1)==() goto Start
SET fromMSBuild=1
:Start
ECHO fromMSBuild:%fromMSBuild%
REM ***** Perform your actions here *****
set theExitCode=101
GOTO End
:End
IF %fromMSBuild%==1 exit %theExitCode%
REM **** Not from MSBuild ****
ECHO Exiting with exit code %theExitCode%
exit /b %theExitCode%
我创建了 MSBuild 文件 wrapper.proj,它是:
<Project DefaultTargets="Demo" ToolsVersion="3.5"
xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<BatchFile>test.bat</BatchFile>
<FromMSBuild>FromMSBuild</FromMSBuild>
</PropertyGroup>
<Target Name="Demo">
<Message Text="Executing batch file $(BatchFile)" Importance="high"/>
<PropertyGroup>
<_Command>$(BatchFile) $(FromMSBuild)</_Command>
</PropertyGroup>
<Exec Command="$(_Command)">
<Output PropertyName="CommandExitCode" TaskParameter="ExitCode"/>
</Exec>
<Message Text="CommandExitCode: $(CommandExitCode)"/>
</Target>
</Project>
如果您从命令提示符执行文件 test.bat,结果是
C:\Data\Development\My Code\Community\MSBuild\BatchFile>test.bat
C:\Data\Development\My Code\Community\MSBuild\BatchFile>ECHO OFF
fromMSBuild:0
Exiting with exit code 101
从 MSBuild 得出的结果是:
C:\Data\Development\My Code\Community\MSBuild\BatchFile>msbuild Wrapper.proj /t:Demo /fl /nologo
Build started 5/18/2009 10:54:52 PM.
Project "C:\Data\Development\My Code\Community\MSBuild\BatchFile\Wrapper.proj" on node 0 (Demo target(s)).
Executing batch file test.bat
fromMSBuild:1
C:\Data\Development\My Code\Community\MSBuild\BatchFile\Wrapper.proj(17,5): error MSB3073: The command "test.bat FromMSBuild" exi
ted with code 101.
Done Building Project "C:\Data\Development\My Code\Community\MSBuild\BatchFile\Wrapper.proj" (Demo target(s)) -- FAILED.
Build FAILED.
"C:\Data\Development\My Code\Community\MSBuild\BatchFile\Wrapper.proj" (Demo target) (1) ->
(Demo target) ->
C:\Data\Development\My Code\Community\MSBuild\BatchFile\Wrapper.proj(17,5): error MSB3073: The command "test.bat FromMSBuild" e
xited with code 101.
0 Warning(s)
1 Error(s)
Time Elapsed 00:00:00.06