Search code examples
continuous-integrationvisual-studio-2017azure-devopspre-build-event

Conditional Prebuild Event Commands


Background

Currently I run a pre-build command when building my solution locally. However, this command isn't needed when building on my VSTS Continuous Integration Server.

Question

Is there a way to only run the pre-build event commands when building on a local machine?

I'm aware you can add conditional statements like below. But is there something to distinguish if its a local build or a CI build?

if $(ConfigurationName) ==  Local 

Solution

  • When using the Visual Studio build task in VSTS you can pass MSBuild parameters from the task configuration. This way you can define your own custom property like RunsOnCI and default it to false. You can then set it to true in your build definition.

    Assume you have the following code in your pre build event:

    if $(BuiltOnCI) == true (
        echo "Hello World!"
    )
    

    You then need to edit your .csproj file and add the BuiltOnCI property with a default value:

    <PropertyGroup>
        ...
        <BuiltOnCI>false</BuiltOnCI>
    </PropertyGroup>
    

    You can test your changes by running MSBuild on the command line. Running it like this will not show the Hello World message:

    msbuild myproject.csproj
    

    Passing the parameter on the command line allows you to set it to true:

    msbuild StackoverflowSample.csproj /p:BuiltOnCi=true
    

    Now that it works locally, you can use /p:BuiltOnCi=true and put in your VSTS task in the MSBuild arguments field.