处理这个问题的一种方法是让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%
我已经创建了一个名为wrapper.proj的MSBuild文件,其内容如下:
<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