How To: Implementing Custom Tasks – Part I

While MSBuild is all about build customization,we never really blogged about what is involved in implementing custom tasks.  Partly, I suppose that's because implementing a custom task is as easy as falling off a log most of the time: 1) Subclass Microsoft.Build.Utilities.Task abstract class 2) Implement the Execute method

But there's a lot more to tasks than just that. In this series of posts, I hope to cover all there is to know about MSBuild tasks - both at a conceptual level as well as on variations such as ToolTask, AppDomainIsolatedTask, etc.  In this post I'd like to set the context for discussing some of those topics.

A task, in principle is nothing more than an implementation of the GoF Command Object Pattern i.e. an object that knows how to perform an action encapsulated via an Execute method. While it is possible to utilize tasks programmatically via code, the primary motivation was to provide a way of performing self standing units of work within build targets.

In the crudest form, a task is a type that implements the Microsoft.Build.Framework.ITask interface from the Microsoft.Build.Framework assembly.  Here's a simple implementation of a task that can set environment variables.

using Microsoft.Build.Framework;

namespace SimpleTask
    public class SetEnvironmentVariable : ITask
        private IBuildEngine engine;              
        public IBuildEngine BuildEngine
            get { return engine; }
            set { engine = value; }

        private ITaskHost host;
        public ITaskHost HostObject
            get { return host; }
            set { host = value; }

        private string name;
        public string Name
            get { return name; }
            set { name = value; }

        private string varValue;

        public string Value
            get { return varValue; }
            set { varValue = value; }

        public bool Execute()
            System.Environment.SetEnvironmentVariable(name, varValue);
            string message = string.Format("Environment Variable {0} set to {1}", name, varValue);
            BuildMessageEventArgs args = new BuildMessageEventArgs(
                message, string.Empty, "SetEnvironmentVariable", MessageImportance.Normal);
            return true;

In addition to the Execute method that performs the actual work, at the minimum all tasks must expose two properties - BuildEngine of type IBuildEngine, and HostObject of type ITaskHost. For the purposes of most tasks, the implementation I have shown here will suffice.

IBuildEngine itself is used by the task to report messages, warnings and errors to the MSBuild engine.  ITaskHost is an interface that is used to represent host objects that can form a basis for richer communication between tasks and an environment that hosts MSBuild (such as Visual Studio).  ITaskHost is extremely useful in cases where you are hosting the build engine yourself.  I will cover the details of this beast in a later post.

.NET properties on a task type allow you define parameters on the task in order to communicate with the task via the project file.  So, in the case of the SetEnvironmentVariable task, I have defined Name and Value properties as inputs into the task. My use of the Required attribute on these two properties ensures that the invocation of the tasks will not be possible without specifying those two parameters. In this context, it makes sense because the task cannot perform its function without having those to values specified to it.

Finally, returning true from the Execute method indicates success to the MSBuild engine. I have ignored the possibility of the task failing in this case to keep it simple - look for more details on this subject alone in a subsequent post.

Here's how the task is invoked from a project file:

<Project xmlns="">
   <UsingTask AssemblyFile="SimpleTasks.dll" TaskName="SimpleTask.SetEnvironmentVariable" />

   <Target Name="MyTarget">
      <SetEnvironmentVariable Name="OutputPath" value="$(OutputPath)" />

That's all there is to defining and using custom tasks. Of course, it is way simpler to derive from the abstract class Microsoft.Build.Utilities.Task that is included in the Microsoft.Build.Utilities assembly, and that's what you should be using most of the time unless you require a richer interaction with the MSBuild engine.

In the next post, I will dig into more details on interacting with tasks via the project file. We will examine the types of objects that can be passed in and out of tasks, caveats to watch out for, etc.

[ Author: Faisal Mohamood ]

Comments (53)

  1. Gauthier Segay says:

    Hi I don’t have digged much on msbuild, it’s great to have a MS supported build tool and find it very similar to the Ant approach.

    By the way, I think your exemple is not working:


    public string Value


    get { return Value; }

    set { varValue = value; }


    it should be:


    public string Value


    get { return varValue; }

    set { varValue = value; }


  2. Mike Fourie says:

    Yes – thanks for pointing out the mistake. I had tried the task out before I posted it – but obviously the get property was not getting used becasue I had not used it as an Output property, and that’s why I didn’t spot the mistake.

    Good catch!

    Faisal Mohamood

  3. Shadi Mari says:

    How can i define two task matually exclusive properties where either one of them is required in case the other is not specified.

    e.g. In a database operation task, either [usename & password] or Trusted_Connection=Yes can be specified.

    I wonder if this is possible in MsBuild?

  4. Introduction

    Ok you have written your custom build task (if not visit MSDN for a starting point or here…

  5. Karine Bosch says:


    I’m developing a nightly build process. Two of the tasks I need to execute, is uninstalling a windows service before the compilation of the sources starts; and installing and registering a windows service when the sources are compiled and before unit testing starts. I’ve created my custom tasks. But how can I define in my build file when these tasks need to execute?

    Kind regards,


  6. Thank you for the nice tutorial. I used it as a reference for creating a custom MSBuild Task to label projects in Visual SourceSafe. I then created a tutorial and published it on my site and at The Code Project. Here is the link:

    I hope others find it useful.

  7. Rathinavelan says:

    Hi all, I have the same issue/request for information as Karine Bosch , I need to be able to stop an installed windows service, and start it, upon successfull deployment in the app server, FYI, I am able to successfully build the application ( web application) in the Build server, and copy it to the app server, and there by deploying the fresh web build.

    Only issue now is this windows server, any help will be appreciated

  8. Sometimes a user might want to add vcbuild commandline optins (such as /useenv (/u)/wrnfile:&amp;lt;file…

  9. Team Build, pour ceux qui n’auraient pas suivi, est le module d’intégration/build de Team System. Il

  10. bankruptcy says:

    All about <a href=" ">amicable bankruptcy scottish</a> <a href=" ">bankruptcy injury kmart lawsuit personal</a> <a href=" ">bankruptcy thermoplastics</a> <a href=" ">cornelius pools bankruptcy</a> [URL=]mikal gilmore bankruptcy[/URL] [URL=]bankruptcy metaldyne[/URL] nice

  11. gifts says:

    Greetings <a href=" ">gift in ireland mcsweeneys today</a> <a href=" ">giftware independent</a> <a href=" ">black masked lovebird gifts</a> <a href=" ">biotherm gift</a> [URL=]pampering gifts for women[/URL] [URL=]ceramic premium gift malaysia[/URL] too

  12. truck new says:

    In bookmarks <a href=" ">tonka monster trucks serial</a> <a href=" ">toyota trucks hompepage</a> <a href=" ">dodge big horn truck</a> <a href=" ">jack rabbit truck topper</a> [URL=]moveing trucks[/URL] [URL=]used pickup trucks in akron ohio[/URL] loves

  13. christmas1 says:

    Funny sites <a href=" ">counted cross stitch christmas ornament</a> <a href=" ">hosta night before christmas</a> <a href=" ">advent calendar christmas lampoons national vacation</a> <a href=" ">felt christmas tree advent calendar</a> [URL=]1996 christmas crystal ornament swarovski[/URL] [URL=]a christmas carol madison square garden[/URL] more

  14. gift4 says:

    All about site <a href=" ">chilis gift certificate</a> <a href=" ">balloon and gift delivery boise idaho</a> <a href=" ">cellophane gift wrap</a> <a href=" ">cleveland fruit and gift basket</a> [URL=]zadie gifts jewish[/URL] [URL=]christmas gift for chef christmas cards hotgiftideasnet[/URL] online

  15. Budu v tope <a href=" ">volkswagen group milton keynes</a> <a href=" ">1999 volkswagen jetta wolfsburg edition</a> <a href=" ">2000 volkswagen jetta gls</a> <a href=" ">volkswagen touareg w12 for sale</a> [URL=]volkswagen diesel 2007[/URL] [URL=]2001 volkswagen golf gls specifications[/URL] and other

  16. mortgage1 says:

    Nice world <a href=" ">vendee mortgage trust</a> <a href=" ">mortgage calculator td</a> <a href=" ">baloon mortgage</a> <a href=" ">sps mortgage</a> [URL=]assumable mortgages alberta[/URL] [URL=]manhatten mortgage[/URL] portals

  17. Hello, people <a href=" ">hsbc credit card login</a> <a href=" ">bmi baby credit card</a> <a href=" ">instant credit card</a> <a href=" ">canadian tire mastercard</a> [URL=]citibank citicards[/URL] [URL=]low intrest credit cards[/URL] best

  18. cadillac says:

    Access <a href=" ">cadillac seville diesel</a> <a href=" ">cadillac seville sts</a> <a href=" ">history of the fleetwood cadillac</a> <a href=" ">1957 cadillac biarritz convertible</a> [URL=]cadillac broughman[/URL] [URL=]feature programming mode cadillac seville 2002[/URL] work

  19. Welcome to <a href=" ">pavones real estate</a> <a href=" ">pagosa springs colorado real estate</a> <a href=" ">nayarit real estate</a> <a href=" ">real estate appraiser license sc</a> [URL=]montelongo real estate[/URL] [URL=]peterborough nh real estate[/URL] more

  20. антимаулнетизм оперативно <a href= >антимаулнетизм надежно</a> [url=]антимаулнетизм надежно[/url]

  21. Looking <a href=" ">painted furniture in the dc metro</a> <a href=" ">office furniture malaysia sdn bhd</a> <a href=" ">hendredon furniture</a> <a href=" ">royce furniture website</a> [URL=]bar furniture georgia[/URL] [URL=]exterior wood furniture[/URL] groove

  22. pizdavsem says:

    Great site! You can find related info on the following sites:

    <a href= >vsem pizda, ya skazal!</a>

  23. pizdavsem says:

    Great site! You can find related info on the following sites:

    <a href= >vsem pizda, ya skazal!</a>

  24. degree mya says:

    Funny sites <a href=" ">school locker organizer</a> <a href=" ">radiologist school jobs lincoln nebraska</a> <a href=" ">ventura college pirates</a> <a href=" ">veggietales preschool curriculum kit</a> [URL=]thelearningchannel[/URL] [URL=]online school for paranormal investigator[/URL] likes

  25. prokuror says:

    <a href = ""&gt;  Заявление</a> – заявление в суд, на данном сайте рассказанно как  правильно составить образец и бланк искового заявления. Публикации и статьи практикующих юристов, большое количество различных образцов и форм составления заявлений.

  26. gerpescom says:

    Герпес – лечить болезнь при помощи антибиотиков. Ресурс будет полезен всем болеющим половым герпесом, а также врачам и аспирантам, и любому кому интересны проблемы герпеса.

  27. Геморрой – лечить болезнь при помощи антибиотиков. Сайт будет полезен всем страдающим анальными трещинами, а также врачам и аспирантам, и любому кому интересны проблемы геморроя. Отдельный раздел ресурса посвящен методам излечения от геморроя при помощи народной медицины.

  28. Климакс – все самое важное и необходимое про климакс. На ваши вопросы про состояние климакса ответят на страницах нашего ресурса практикующие врачи геронтологи высшей квалификации. Наш сайт подробно расскажет вам о том, что такое предклимакс и почему климакс еще называют менопаузой, мы рассматриваем как изменяется  форма и функциональность груди, какие проблемы могут возникнуть со зрением. Новый раздел нашего сайта представляет информацию о подготовке к  наступлению климакса, также есть информация про правильное питание во время климакса.

    Главное знать – ничего страшного в климаксе нет, климакса не нужно бояться. Климакс или Менопауза это все лишь новое состояние вашего организма.

  29. David Savage says:

    A look at the top 6 things that I think all developers should know by 2010.

  30. Ryan McLean says:

    Is there a default timeout impletemented y MSBuild for a custom task and if so can it be overridden?

    I have a custom task that calls uses weblcient.downloadfile to download a 900Mb file, the code works fie if run from a c# console program but if I call it from an MSBuild script as a Custom Task then it fails after 30seconds.



  31. Ryan McLean says:

    Actually never mind, turns out it was the IDE I was using that was timing out and killing MSBuild

  32. Anthony Harrison says:

    Thanks Mike, this is still relevant in 2015. 9 years later, great post!

Skip to main content