Trident D'Gao
Trident D'Gao

Reputation: 19762

How can I pass a key-value set of parameters to a task in MsBuild?

I have a custom task that requires a set of key-values in order to work. How can I get a custom MSBuild configurable with a string-to-string dictionary sort of configuration?

Upvotes: 1

Views: 835

Answers (2)

Mark Arnott
Mark Arnott

Reputation: 1994

If you have a set number of key value pairs where the keys don't change but the values do, you could use good old fashion environment variables to accomplish this.

@ECHO OFF
SET K1=Value1
SET K2=Value2

MSBUILD.EXE mytest.proj

Then in your mytest.proj file you have something like :

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="ATest" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">

<Target Name="ATest">
  <Message Text="-- $(K1) --"/>
  <Message Text="-- $(K2) --"/>
</Target>    

Upvotes: 0

seva titov
seva titov

Reputation: 11920

There is no built-in dictionaries in MSBuild, but you can make up your own that would behave almost like a dictionary. There are several options, but the semantically the closest one would be to use use an item group with metadata for key and value.

Your MSBuild file might look like this:

<ItemGroup>
  <MyDictionary Include="Value1">
    <MyKey>key1</MyKey>
  </MyDictionary>
  <MyDictionary Include="Value2">
    <MyKey>key2</MyKey>
  </MyDictionary>
  ...
  <MyDictionary Include="ValueN">
    <MyKey>keyN</MyKey>
  </MyDictionary>
</ItemGroup>

<Target Name="MyTarget">
  <MyTask MyInput="@(MyDictionary)" ... />
</Target>

Your custom task will simply take an input of ITaskItem[] array, and you can iterate through it to convert it to real Dictionary if you need to:

class MyTask: ITask
{
    public ITaskItem[] MyInput { get; set; }

    public override bool Execute()
    {
        ...
        var dic = new Dictionary<string, string>();
        foreach (var input in MyInput)
        {
            dic.Add(input.GetMetadata("MyKey"), input.ItemSpec);
        }
        ...
    }
}

Note that ItemGroup does not guarantee one to one mapping between keys and values, so you might end up with multiple values for the same key.

Upvotes: 2

Related Questions