Skip to content
Yevhen Bobrov edited this page Apr 3, 2020 · 1 revision

Running external MSBuild tasks

To make the transitioning from MSBuild easier, Nake comes with the ability to execute any external MSBuild task. You can simply reference any .NET dll, which contains MSBuild tasks (such as CommunityTasks or ExtensionPack) and execute any task by using Exec() extension method.

#r "Packages\MSBuildTasks.1.4.0.56\tools\MSBuild.Community.Tasks.dll"

using Nake;
using MSBuild.Community.Tasks.Xml;

[Task] void UpdateWebConfig()
{
    new XmlMassUpdate
    {
         ContentFile = "{OutputPath}\web.config",
         SubstitutionsFile = "{SubstitutionsFilePath}", 
         ContentRoot = "/configuration",
         SubstitutionsRoot = "/configuration/substitutions/{Configuration}"
    }
   .Exec();
}

The MSBuild() function above, will also return the given task back, after execution. This allows you to inspect any Output properties of the task, so you can easily obtain any task outputs (results).

var xmlUpdate = new XmlMassUpdate
{
     ContentFile = "{OutputPath}\web.config",
     SubstitutionsFile = "{SubstitutionsFilePath}", 
     ContentRoot = "/configuration",
     SubstitutionsRoot = "/configuration/substitutions/{Configuration}"
}
.Exec();

Console.WriteLine(xmlUpdate.ContentPathUsedByTask);
Console.WriteLine(xmlUpdate.MergedPathUsedByTask);
Console.WriteLine(xmlUpdate.SubstitutionsPathUsedByTask);

There also set of extension methods exposed to help you deal with conversion from string to ITaskItem object (which is usually expected by MSBuild tasks):

using MSBuild.ExtensionPack.SqlServer;

void RunSql(string dbName, string[] sqlFiles)
{
    new SqlCmd
    {
        InputFiles = sqlFiles.AsTaskItems(), // this extension method converts strings to task items
        Server = "localhost",
        TaskAction = "Execute",
        SeverityLevel = 5,
        Database = dbName
    }
    .Exec();
}

void CreateDatabase(string dbName)
{
    new MsSqlServerDatabase
    {
        DatabaseItem = dbName.AsTaskItem(),
        TaskAction = "Create",
        CompatibilityLevel = "110",
        MachineName = "localhost",
        Collation = "Cyrillic_General_CI_AS"
    }
    .Exec();
}
Clone this wiki locally