Is there a way to list all the build targets available in a build file?

后端 未结 2 385
梦如初夏
梦如初夏 2021-02-05 09:23

Given a build file (.csproj or msbuild.xml or whatever), I\'d like to run a msbuild command that lists all the available, defined targets.

Does that function exist?

2条回答
  •  情歌与酒
    2021-02-05 10:05

    Using MSBuild 2.0/3.5 : Custom Task

    You could write a custom msbuild task like this :

    using System;
    using System.Collections.Generic;
    using Microsoft.Build.BuildEngine;
    using Microsoft.Build.Framework;
    using Microsoft.Build.Utilities;
    
    namespace MSBuildTasks
    {
      public class GetAllTargets : Task
      {
        [Required]
        public String ProjectFile { get; set; }
    
        [Output]
        public ITaskItem[] Targets { get; set; }
    
        public override bool Execute()
        {
          var project = new Project(BuildEngine as Engine);
          project.Load(ProjectFile);
    
          var taskItems = new List(project.Targets.Count);
          foreach (Target target in project.Targets)
          {
            var metadata = new Dictionary
                            {
                              {"Condition", target.Condition},
                              {"Inputs", target.Inputs},
                              {"Outputs", target.Outputs},
                              {"DependsOnTargets", target.DependsOnTargets}
                            };
            taskItems.Add(new TaskItem(target.Name, metadata));
          }
    
          Targets = taskItems.ToArray();
    
          return true;
        }
      }
    }    
    

    That you'll use like that:

    
      
        
      
    
      
    
    

    Using MSBuild 4.0 : Inline task

    With MSBuild 4 you could use the new shiny thing : the inline task. Inline task allows you to define the behavior directly in msbuild file.

    
      
        
        
      
      
        
        
        
        
        
        
        
        
          (project.Targets.Count);
            foreach (KeyValuePair kvp in project.Targets)
            {
              var target = kvp.Value;
              var metadata = new Dictionary
                              {
                                {"Condition", target.Condition},
                                {"Inputs", target.Inputs},
                                {"Outputs", target.Outputs},
                                {"DependsOnTargets", target.DependsOnTargets}
                              };
              taskItems.Add(new TaskItem(kvp.Key, metadata));
            }
    
            TargetsOut = taskItems.ToArray();
          ]]>
        
      
    
    
    
      
          
      
    
      
    
    

提交回复
热议问题