How to access the msbuild command line parameters from within the project file being processed?

非 Y 不嫁゛ 提交于 2019-12-03 17:38:50

问题


I need to get access to the msbuild command line parameters (the specified targets and properties in particular) from within the project file being processed in order to pass them down to the Properties of an <MSBuild> task.

My msbuild file uses a large number of properties, and I don't know ahead of time which ones will be overridden via the command line, so I'm looking for a way to pass these down without specifying each one manually to the Properties of the <MSBuild> task. Something like the $* variable in a bat file.

How can I accomplish this?


回答1:


This question is ancient, but FWIW here is how I have handled getting the MSBuild command line parameters:

Option 1 (not recommended)

$([System.Environment]::CommandLine.Trim())

The problem is that this will cause the following error when using dotnet build.

'MSB4185: The function "CommandLine" on type "System.Environment" is not available for execution as an MSBuild property function.'

Option 2 (FTW)

Create a Task

using System;
using System.Linq;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;

public sealed class GetCommandLineArgs : Task {
    [Output]
    public ITaskItem[] CommandLineArgs { get; private set; }

    public override bool Execute() {
        CommandLineArgs = Environment.GetCommandLineArgs().Select(a => new TaskItem(a)).ToArray();
        return true;
    }
}

Use the Task to create an Item for each argument

<GetCommandLineArgs>
  <Output TaskParameter="CommandLineArgs" ItemName="CommandLineArg" />
</GetCommandLineArgs>

Optionally, reconstruct the arguments into a single string

<PropertyGroup>
  <CommandLineArgs>@(CommandLineArg, ' ')</CommandLineArgs>
<PropertyGroup>


来源:https://stackoverflow.com/questions/3260913/how-to-access-the-msbuild-command-line-parameters-from-within-the-project-file-b

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!