逐步解說:使用 MSBuildWalkthrough: Use MSBuild

MSBuild 是 Microsoft 和 Visual Studio 的建置平台。MSBuild is the build platform for Microsoft and Visual Studio. 此逐步解說將介紹 MSBuild 的建置區塊,以及示範如何撰寫和管理 MSBuild 專案及進行偵錯。This walkthrough introduces you to the building blocks of MSBuild and shows you how to write, manipulate, and debug MSBuild projects. 學習內容:You will learn about:

  • 建立和管理專案檔。Creating and manipulating a project file.

  • 如何使用組建屬性How to use build properties

  • 如何使用組建項目。How to use build items.

您可以從 Visual Studio 或命令視窗執行 MSBuild。You can run MSBuild from Visual Studio, or from the Command Window. 在本逐步解說中,您將使用 Visual Studio 來建立 MSBuild 專案檔。In this walkthrough, you create an MSBuild project file using Visual Studio. 您可以在 Visual Studio 中編輯專案檔,然後使用命令視窗建置專案並檢查結果。You edit the project file in Visual Studio, and use the Command Window to build the project and examine the results.

建立 MSBuild 專案Create an MSBuild project

Visual Studio 專案系統是以 MSBuild 為基礎。The Visual Studio project system is based on MSBuild. 這可讓您輕鬆地使用 Visual Studio 建立新的專案檔。This makes it easy to create a new project file using Visual Studio. 在本節中,您將建立 Visual C# 專案檔。In this section, you create a Visual C# project file. 您可以選擇改為建立 Visual Basic 專案檔。You can choose to create a Visual Basic project file instead. 在本逐步解說的內容中,這兩個專案檔之間的差異非常小。In the context of this walkthrough, the difference between the two project files is minor.

建立專案檔To create a project file

  1. 開啟 Visual Studio 並建立專案。Open Visual Studio and create a project.

    Esc 關閉開始視窗。Press Esc to close the start window. 鍵入 Ctrl + Q 來開啟搜尋方塊,鍵入 winforms,然後選擇 [建立新的 Windows Forms App (.NET Framework)]。Type Ctrl + Q to open the search box, type winforms, then choose Create a new Windows Forms App (.NET Framework). 在出現的對話方塊中選擇 [建立]。In the dialog box that appears, choose Create.

    在 [名稱] 方塊中,輸入 BuildAppIn the Name box, type BuildApp. 輸入方案的 [位置],例如 D:\Enter a Location for the solution, for example, D:\. 接受預設的 [解決方案]、[解決方案名稱] (BuildApp) 和 [架構]。Accept the defaults for Solution, Solution Name (BuildApp), and Framework.

    從頂端功能表列中,選擇 [檔案] > [新增] > [專案]。From the top menu bar, choose File > New > Project. 在 [新增專案] 對話方塊的左窗格中,展開 [Visual C#] > [Windows Desktop],然後選擇 [Windows Forms App (.NET Framework)]。In the left pane of the New Project dialog box, expand Visual C# > Windows Desktop, then choose Windows Forms App (.NET Framework). 然後選擇 [確定]。Then choose OK.

    在 [名稱] 方塊中,輸入 BuildAppIn the Name box, type BuildApp. 輸入方案的 [位置],例如 D:\Enter a Location for the solution, for example, D:\. 接受 [為方案建立目錄] (已選取)、[加入至原始檔控制] (未選取) 及 [方案名稱] (BuildApp) 的預設值。Accept the defaults for Create directory for solution (selected), Add to Source Control (not selected), and Solution Name (BuildApp).

  2. 按一下 [確定] 或 [建立] 來建立專案檔。Click OK or Create to create the project file.

檢查專案檔Examine the project file

在上一節中,您使用了 Visual Studio 來建立 Visual C# 專案檔。In the previous section, you used Visual Studio to create a Visual C# project file. 專案檔會在 [方案總管] 中,透過名為 BuildApp 的專案節點來顯示。The project file is represented in Solution Explorer by the project node named BuildApp. 您可以使用 Visual Studio 程式碼編輯器來檢查專案檔。You can use the Visual Studio code editor to examine the project file.

檢查專案檔To examine the project file

  1. 在 [方案總管] 中,按一下專案節點 BuildAppIn Solution Explorer, click the project node BuildApp.

  2. 在 [屬性] 瀏覽器中,請注意 [專案檔] 屬性為 BuildApp.csprojIn the Properties browser, notice that the Project File property is BuildApp.csproj. 所有專案檔名稱的尾碼都是 projAll project files are named with the suffix proj. 如果您已建立 Visual Basic 專案,則專案檔名稱會是 BuildApp.vbprojIf you had created a Visual Basic project, the project file name would be BuildApp.vbproj.

  3. 以滑鼠右鍵按一下專案節點,然後按一下 [卸載專案]。Right-click the project node, then click Unload Project.

  4. 再次以滑鼠右鍵按一下專案節點,然後按一下 [編輯 BuildApp.csproj]。Right-click the project node again, then click Edit BuildApp.csproj.

    該專案檔隨即出現在程式碼編輯器中。The project file appears in the code editor.

目標和工作Targets and tasks

專案檔是含有根節點 Project 的 XML 格式檔案。Project files are XML-formatted files with the root node Project.

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

您必須在 Project 項目中指定 xmlns 命名空間。You must specify the xmlns namespace in the Project element. 若新專案中存在 ToolsVersion,其必須為 "15.0"。If ToolsVersion is present in a new project, it must be "15.0".

建置應用程式的工作是利用 TargetTask 項目來完成。The work of building an application is done with Target and Task elements.

  • 工作 (Task) 是工作 (Work) 的最小單位,也就是組建的「元素」。A task is the smallest unit of work, in other words, the "atom" of a build. 工作是獨立的可執行檔元件,其中可能會有輸入和輸出。Tasks are independent executable components which may have inputs and outputs. 專案檔中沒有任何目前參考或定義的工作。There are no tasks currently referenced or defined in the project file. 您會在下列各節中將工作加入至專案檔。You add tasks to the project file in the sections below. 如需詳細資訊,請參閱工作 主題。For more information, see the Tasks topic.

  • 目標是一連串具名的工作。A target is a named sequence of tasks. 如需詳細資訊,請參閱目標主題。For more information, see the Targets topic.

預設目標並未在專案檔中定義。The default target is not defined in the project file. 而是在匯入的專案中指定。Instead, it is specified in imported projects. Import 元素會指定匯入的專案。The Import element specifies imported projects. 例如,在 C# 專案中,預設目標會從檔案 Microsoft.CSharp.targets 匯入。For example, in a C# project, the default target is imported from the file Microsoft.CSharp.targets.

<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />

只要參考到它們,就能有效地將匯入的檔案插入至專案檔。Imported files are effectively inserted into the project file wherever they are referenced.

Note

.NET Core 等部分專案類型會使用具 Sdk 屬性而非 ToolsVersion 屬性的簡化結構描述。Some project types, such as .NET Core, use a simplified schema with an Sdk attribute instead of ToolsVersion. 這些專案均具有隱含的匯入與不同的預設屬性值。These projects have implicit imports and different default attribute values.

MSBuild 會持續追蹤組建的目標,並保證每個目標的建置不會超過一次。MSBuild keeps track of the targets of a build, and guarantees that each target is built no more than once.

加入目標和工作Add a target and a task

將目標加入至專案檔。Add a target to the project file. 將工作加入至會印出訊息的目標。Add a task to the target that prints out a message.

加入目標和工作To add a target and a task

  1. 將下列這幾行加入至專案檔,緊接在 Import 陳述式之後:Add these lines to the project file, just after the Import statement:

    <Target Name="HelloWorld">
    </Target>
    

    這會建立名為 HelloWorld 的目標。This creates a target named HelloWorld. 請注意,您在編輯專案檔時必須具備 IntelliSense 支援。Notice that you have IntelliSense support while editing the project file.

  2. 將這幾行加入至 HelloWorld 目標,因此,產生的區段會看起來如下:Add lines to the HelloWorld target, so that the resulting section looks like this:

    <Target Name="HelloWorld">
      <Message Text="Hello"></Message>  <Message Text="World"></Message>
    </Target>
    
  3. 儲存專案檔。Save the project file.

Message 工作是 MSBuild 隨附的許多工作之一。The Message task is one of the many tasks that ships with MSBuild. 如需可用工作的完整清單和用法資訊,請參閱工作參考For a complete list of available tasks and usage information, see Task reference.

Message 工作會取得 Text 屬性的字串值做為輸入,並顯示於輸出裝置上。The Message task takes the string value of the Text attribute as input and displays it on the output device. HelloWorld 目標會執行 Message 工作兩次:第一次顯示 "Hello",接著顯示 "World"。The HelloWorld target executes the Message task twice: first to display "Hello", and then to display "World".

建置目標Build the target

從 Visual Studio 的 [開發人員命令提示字元] 執行 MSBuild,以建置前述內容所定義的 HelloWorld 目標。Run MSBuild from the Developer Command Prompt for Visual Studio to build the HelloWorld target defined above. 使用 -target 或 -t 命令列參數選取目標。Use the -target or -t command line switch to select the target.

Note

我們會在下列各節中,將開發人員命令提示字元稱為命令視窗We will refer to the Developer Command Prompt as the Command Window in the sections below.

建置目標To build the target

  1. 開啟 [命令視窗]。Open the Command Window.

    (Windows 10) 在工作列的搜尋方塊中開始鍵入工具名稱,例如 devdeveloper command prompt(Windows 10) In the search box on the taskbar, start typing the name of the tool, such as dev or developer command prompt. 這會顯示符合搜尋模式的已安裝應用程式清單。This brings up a list of installed apps that match your search pattern.

    如果您需要以手動方式尋找,檔案是 LaunchDevCmd.bat,位於 <visualstudio 安裝資料夾><版本>\Common7\Tools 資料夾。If you need to find it manually, the file is LaunchDevCmd.bat in the <visualstudio installation folder><version>\Common7\Tools folder.

  2. 從命令視窗,瀏覽至包含專案檔的資料夾,在此案例中為 D:\BuildApp\BuildAppFrom the command window, navigate to the folder containing the project file, in this case, D:\BuildApp\BuildApp.

  3. 使用命令參數 -t:HelloWorld 執行 msbuild。Run msbuild with the command switch -t:HelloWorld. 這會選取並建置 HelloWorld 目標:This selects and builds the HelloWorld target:

    msbuild buildapp.csproj -t:HelloWorld
    
  4. 檢查 [命令視窗] 中的輸出。Examine the output in the Command window. 您應該會看到 "Hello" 和 "World" 這兩行:You should see the two lines "Hello" and "World":

    Hello
    World
    

Note

如果您看到了 The target "HelloWorld" does not exist in the project,則您可能忘了在程式碼編輯器中儲存該專案檔。If instead you see The target "HelloWorld" does not exist in the project then you probably forgot to save the project file in the code editor. 請儲存檔案,然後再試一次。Save the file and try again.

藉由交替使用程式碼編輯器和命令視窗,您可以變更專案檔,並快速查看結果。By alternating between the code editor and the command window, you can change the project file and quickly see the results.

組建屬性Build properties

組建屬性是會引導組建的名稱/值組。Build properties are name-value pairs that guide the build. 專案檔頂端已經定義了數個組建屬性:Several build properties are already defined at the top of the project file:

<PropertyGroup>
...
  <ProductVersion>10.0.11107</ProductVersion>
  <SchemaVersion>2.0</SchemaVersion>
  <ProjectGuid>{30E3C9D5-FD86-4691-A331-80EA5BA7E571}</ProjectGuid>
  <OutputType>WinExe</OutputType>
...
</PropertyGroup>

所有屬性都是 PropertyGroup 項目的子項目。All properties are child elements of PropertyGroup elements. 屬性的名稱是子項目的名稱,而屬性的值是子項目的文字項目。The name of the property is the name of the child element, and the value of the property is the text element of the child element. 例如,套用至物件的For example,

<TargetFrameworkVersion>v15.0</TargetFrameworkVersion>

會定義名為 TargetFrameworkVersion 的屬性,並賦予其字串值 "v15.0"。defines the property named TargetFrameworkVersion, giving it the string value "v15.0".

您隨時都能重新定義組建屬性。Build properties may be redefined at any time. 如果If

<TargetFrameworkVersion>v3.5</TargetFrameworkVersion>

稍後出現在專案檔中,或在稍後會於專案檔中匯入的檔案中,則 TargetFrameworkVersion 會採用新值 "v3.5"。appears later in the project file, or in a file imported later in the project file, then TargetFrameworkVersion takes the new value "v3.5".

檢查屬性值Examine a property value

若要取得屬性的值,請使用下列語法,其中 PropertyName 是屬性的名稱:To get the value of a property, use the following syntax, where PropertyName is the name of the property:

$(PropertyName)

使用此語法來檢查專案檔中的某些屬性。Use this syntax to examine some of the properties in the project file.

檢查屬性值To examine a property value

  1. 從程式碼編輯器,使用此程式碼來取代 HelloWorld 目標:From the code editor, replace the HelloWorld target with this code:

    <Target Name="HelloWorld">
      <Message Text="Configuration is $(Configuration)" />
      <Message Text="MSBuildToolsPath is $(MSBuildToolsPath)" />
    </Target>
    
  2. 儲存專案檔。Save the project file.

  3. 從 [命令視窗],輸入並執行這一行:From the Command Window, enter and execute this line:

    msbuild buildapp.csproj -t:HelloWorld
    
  4. 檢查輸出結果,Examine the output. 您應該會看到這兩行 (您的 .NET Framework 版本可能不一樣):You should see these two lines (your .NET Framework version may differ):

    Configuration is Debug
    MSBuildToolsPath is C:\Program Files (x86)\Microsoft Visual Studio\2019\<Visual Studio SKU>\MSBuild\15.0\Bin
    
    Configuration is Debug
    MSBuildToolsPath is C:\Program Files (x86)\Microsoft Visual Studio\2017\<Visual Studio SKU>\MSBuild\15.0\Bin
    

Note

如果您未看見這幾行,則您可能忘了在程式碼編輯器中儲存該專案檔。If you don't see these lines then you probably forgot to save the project file in the code editor. 請儲存檔案,然後再試一次。Save the file and try again.

條件式屬性Conditional properties

有條件地定義許多屬性 (例如 Configuration),也就是 Condition 屬性會出現在屬性項目中。Many properties like Configuration are defined conditionally, that is, the Condition attribute appears in the property element. 只有當條件評估為 "true" 時,才能定義或重新定義條件式屬性。Conditional properties are defined or redefined only if the condition evaluates to "true". 請注意,未定義屬性的預設值是空字串。Note that undefined properties are given the default value of an empty string. 例如,套用至物件的For example,

<Configuration   Condition=" '$(Configuration)' == '' ">Debug</Configuration>

表示「如果尚未定義 Configuration 屬性,請加以定義,並提供值 'Debug'」。means "If the Configuration property has not been defined yet, define it and give it the value 'Debug'".

幾乎所有的 MSBuild 項目都會有一個 Condition 屬性。Almost all MSBuild elements can have a Condition attribute. 如需使用 Condition 屬性的詳細討論,請參閱條件For more discussion about using the Condition attribute, see Conditions.

保留的屬性Reserved properties

MSBuild 保留一些屬性名稱來儲存專案檔和 MSBuild 二進位檔案的相關資訊。MSBuild reserves some property names to store information about the project file and the MSBuild binaries. MSBuildToolsPath 是保留的屬性範例。MSBuildToolsPath is an example of a reserved property. 保留的屬性是使用 $ 標記法來參考,如同任何其他屬性。Reserved properties are referenced with the $ notation like any other property. 如需詳細資訊,請參閱如何:參考專案檔的名稱或位置MSBuild 保留和已知的屬性For more information, see How to: Reference the name or location of the project file and MSBuild reserved and well-known properties.

環境變數Environment variables

您可以使用和組建屬性一樣的方式,來參考專案檔中的環境變數。You can reference environment variables in project files the same way as build properties. 例如,若要在專案檔中使用 PATH 環境變數,請使用 $(Path)。For example, to use the PATH environment variable in your project file, use $(Path). 如果專案包含與環境變數相同名稱的專案定義,則專案中的屬性會覆寫環境變數的值。If the project contains a property definition that has the same name as an environment variable, the property in the project overrides the value of the environment variable. 如需詳細資訊,請參閱如何:在組建中使用環境變數For more information, see How to: Use environment variables in a build.

從命令列設定屬性Set properties from the command line

您可以在命令列上,使用 -property 或 -p 命令列參數定義屬性。Properties may be defined on the command line using the -property or -p command line switch. 接收自命令列的屬性值會覆寫專案檔和環境變數中所設定的屬性值。Property values received from the command line override property values set in the project file and environment variables.

從命令列設定專案值To set a property value from the command line

  1. 從 [命令視窗],輸入並執行這一行:From the Command Window, enter and execute this line:

    msbuild buildapp.csproj -t:HelloWorld -p:Configuration=Release
    
  2. 檢查輸出結果,Examine the output. 您應該會看到下列這一行:You should see this line:

    Configuration is Release.
    

MSBuild 會建立 Configuration 屬性,並提供值 "Release"。MSBuild creates the Configuration property and gives it the value "Release".

特殊字元Special characters

在 MSBuild 專案檔中,有某些字元具有特殊意義。Certain characters have special meaning in MSBuild project files. 這些字元範例包括分號 (;) 和星號 (*)。Examples of these characters include semicolons (;) and asterisks (*). 若要使用這些特殊字元作為專案檔中的常值,就必須使用 %<xx> 語法來指定它們,其中 <xx> 代表字元的 ASCII 十六進位值。In order to use these special characters as literals in a project file, they must be specified by using the syntax %<xx>, where <xx> represents the ASCII hexadecimal value of the character.

變更 Message 工作以顯示具有特殊字元的 Configuration 屬性值,讓它更容易閱讀。Change the Message task to show the value of the Configuration property with special characters to make it more readable.

在 Message 工作中使用特殊字元To use special characters in the Message task

  1. 從程式碼編輯器,使用下列這一行來取代這兩個 Message 工作:From the code editor, replace both Message tasks with this line:

    <Message Text="%24(Configuration) is %22$(Configuration)%22" />
    
  2. 儲存專案檔。Save the project file.

  3. 從 [命令視窗],輸入並執行這一行:From the Command Window, enter and execute this line:

    msbuild buildapp.csproj -t:HelloWorld
    
  4. 檢查輸出結果,Examine the output. 您應該會看到下列這一行:You should see this line:

    $(Configuration) is "Debug"
    

如需詳細資訊,請參閱 MSBuild 特殊字元For more information, see MSBuild special characters.

組建項目Build items

項目是一種資訊,通常是檔案名稱,可用來做為建置系統的輸入。An item is a piece of information, typically a file name, that is used as an input to the build system. 例如,可能會將代表原始程式檔的項目集合傳遞至名為 Compile 的工作,以便將它們編譯為組件。For example, a collection of items representing source files might be passed to a task named Compile to compile them into an assembly.

所有項目 (Item) 都是 ItemGroup 項目 (Element) 的子項目 (Element)。All items are child elements of ItemGroup elements. 項目 (Item) 名稱是子項目 (Element) 的名稱,而項目 (Item) 值是子項目 (Element) 的 Include 屬性值。The item name is the name of the child element, and the item value is the value of the Include attribute of the child element. 系統會將名稱相同的項目值收集到該名稱的項目類型。The values of items with the same name are collected into item types of that name. 例如,套用至物件的For example,

<ItemGroup>
    <Compile Include="Program.cs" />
    <Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>

定義一個包含兩個項目的項目群組。defines an item group containing two items. Compile 項目類型有兩個值:Program.csProperties\AssemblyInfo.csThe item type Compile has two values: Program.cs and Properties\AssemblyInfo.cs.

下列程式碼會在一個 Include 屬性中宣告這兩個檔案 (以分號分隔),藉以建立相同的項目類型。The following code creates the same item type by declaring both files in one Include attribute, separated by a semicolon.

<ItemGroup>
    <Compile Include="Program.cs;Properties\AssemblyInfo.cs" />
</ItemGroup>

如需詳細資訊,請參閱項目For more information, see Items.

Note

檔案路徑會相對於包含 MSBuild 專案檔的資料夾。File paths are relative to the folder containing the MSBuild project file.

檢查項目類型值Examine item type values

若要取得項目類型的值,請使用下列語法,其中 ItemType 為項目類型的名稱:To get the values of an item type, use the following syntax, where ItemType is the name of the item type:

@(ItemType)

使用此語法來檢查專案檔中的 Compile 項目類型。Use this syntax to examine the Compile item type in the project file.

檢查項目類型值To examine item type values

  1. 從程式碼編輯器,使用下列程式碼來取代 HelloWorld 目標工作:From the code editor, replace the HelloWorld target task with this code:

    <Target Name="HelloWorld">
      <Message Text="Compile item type contains @(Compile)" />
    </Target>
    
  2. 儲存專案檔。Save the project file.

  3. 從 [命令視窗],輸入並執行這一行:From the Command Window, enter and execute this line:

    msbuild buildapp.csproj -t:HelloWorld
    
  4. 檢查輸出結果,Examine the output. 您應該會看到下列這一長串的內容:You should see this long line:

    Compile item type contains Form1.cs;Form1.Designer.cs;Program.cs;Properties\AssemblyInfo.cs;Properties\Resources.Designer.cs;Properties\Settings.Designer.cs
    

預設會以分號分隔項目類型的值。The values of an item type are separated with semicolons by default.

若要變更項目類型的分隔符號,請使用下列語法,其中 ItemType 是項目類型,而 Separator 是一或多個分隔字元的字串:To change the separator of an item type, use the following syntax, where ItemType is the item type and Separator is a string of one or more separating characters:

@(ItemType, Separator)

變更 Message 工作來使用歸位字元和換行字元 (%0A%0D),以便每行顯示一個 Compile 項目。Change the Message task to use carriage returns and line feeds (%0A%0D) to display Compile items one per line.

每行顯示一個項目類型值To display item type values one per line

  1. 從程式碼編輯器,使用下列這一行來取代 Message 工作:From the code editor, replace the Message task with this line:

    <Message Text="Compile item type contains @(Compile, '%0A%0D')" />
    
  2. 儲存專案檔。Save the project file.

  3. 從 [命令視窗],輸入並執行這一行:From the Command Window, enter and execute this line:

    msbuild buildapp.csproj -t:HelloWorld
    
  4. 檢查輸出結果,Examine the output. 您應該會看到下列這幾行:You should see these lines:

    Compile item type contains Form1.cs
    Form1.Designer.cs
    Program.cs
    Properties\AssemblyInfo.cs
    Properties\Resources.Designer.cs
    Properties\Settings.Designer.cs
    

Include、Exclude 和萬用字元Include, Exclude, and wildcards

您可以使用萬用字元 "*"、"**" 及 "?" 搭配 Include 屬性,來將項目加入至項目類型。You can use the wildcards "*", "**", and "?" with the Include attribute to add items to an item type. 例如,套用至物件的For example,

<Photos Include="images\*.jpeg" />

images 資料夾中所有副檔名為 .jpeg 的檔案加入至 Photos 項目類型,同時adds all files with the file extension .jpeg in the images folder to the Photos item type, while

<Photos Include="images\**\*.jpeg" />

images 資料夾及其所有子資料夾中所有副檔名為 .jpeg 的檔案加入至 Photos 項目類型。adds all files with the file extension .jpeg in the images folder, and all its subfolders, to the Photos item type. 如需更多範例,請參閱如何:選取要建置的檔案For more examples, see How to: Select the files to build.

請注意,宣告項目時,會將它們加入至項目類型。Notice that as items are declared they are added to the item type. 例如,套用至物件的For example,

<Photos Include="images\*.jpeg" />
<Photos Include="images\*.gif" />

建立名為 Photo 的項目類型,其中包含 [images] 資料夾中副檔名為 .jpeg.gif 的所有檔案。creates an item type named Photo containing all files in the images folder with a file extension of either .jpeg or .gif. 這就相當於下列這一行:This is equivalent to the following line:

<Photos Include="images\*.jpeg;images\*.gif" />

您可以使用 Exclude 屬性,從項目類型中排除項目。You can exclude an item from an item type with the Exclude attribute. 例如,套用至物件的For example,

<Compile Include="*.cs" Exclude="*Designer*">

將副檔名為 .cs 的所有檔案加入至 Compile 項目類型,但名稱包含 Designer 字串的檔案除外。adds all files with the file extension .cs to the Compile item type, except for files whose names contain the string Designer. 如需更多範例,請參閱如何:從組建中排除檔案For more examples, see How to: Exclude files from the build.

Exclude 屬性只會影響包含這兩者之 Item 項目 (Element) 中由 Include 屬性所加入的項目 (Item)。The Exclude attribute only affects the items added by the Include attribute in the item element that contains them both. 例如,套用至物件的For example,

<Compile Include="*.cs" />
<Compile Include="*.res" Exclude="Form1.cs">

不會排除 Form1.cs 檔,這是在前一個 Item 項目中加入的檔案。would not exclude the file Form1.cs, which was added in the preceding item element.

包含與排除項目To include and exclude items

  1. 從程式碼編輯器,使用下列這一行來取代 Message 工作:From the code editor, replace the Message task with this line:

    <Message Text="XFiles item type contains @(XFiles)" />
    
  2. 加入這個項目 (Item) 群組,緊接在 Import 項目 (Element) 之後:Add this item group just after the Import element:

    <ItemGroup>
       <XFiles Include="*.cs;properties/*.resx" Exclude="*Designer*" />
    </ItemGroup>
    
  3. 儲存專案檔。Save the project file.

  4. 從 [命令視窗],輸入並執行這一行:From the Command Window, enter and execute this line:

    msbuild buildapp.csproj -t:HelloWorld
    
  5. 檢查輸出結果,Examine the output. 您應該會看到下列這一行:You should see this line:

    XFiles item type contains Form1.cs;Program.cs;Properties/Resources.resx
    

項目中繼資料Item metadata

除了 Include 和 Exclude 屬性所收集的資訊之外,項目可能還會包含中繼資料。Items may contain metadata in addition to the information gathered from the Include and Exclude attributes. 若工作需要更多關於項目的資訊 (而不只是項目值),就能使用此中繼資料。This metadata can be used by tasks that require more information about items than just the item value.

在專案檔中宣告項目 (Item) 中繼資料的方式,就是建立一個具有中繼資料名稱的項目 (Element),做為項目 (Item) 的子項目 (Element)。Item metadata is declared in the project file by creating an element with the name of the metadata as a child element of the item. 項目可以有零或多個中繼資料值。An item can have zero or more metadata values. 例如,下列 CSFile 項目具有值為 "Fr" 的 Culture 中繼資料:For example, the following CSFile item has Culture metadata with a value of "Fr":

<ItemGroup>
    <CSFile Include="main.cs">
        <Culture>Fr</Culture>
    </CSFile>
</ItemGroup>

若要取得項目類型的中繼資料值,請使用下列語法,其中 ItemType 是項目類型的名稱,而 MetaDataName 是中繼資料的名稱:To get the metadata value of an item type, use the following syntax, where ItemType is the name of the item type and MetaDataName is the name of the metadata:

%(ItemType.MetaDataName)

檢查項目中繼資料To examine item metadata

  1. 從程式碼編輯器,使用下列這一行來取代 Message 工作:From the code editor, replace the Message task with this line:

    <Message Text="Compile.DependentUpon: %(Compile.DependentUpon)" />
    
  2. 儲存專案檔。Save the project file.

  3. 從 [命令視窗],輸入並執行這一行:From the Command Window, enter and execute this line:

    msbuild buildapp.csproj -t:HelloWorld
    
  4. 檢查輸出結果,Examine the output. 您應該會看到下列這幾行:You should see these lines:

    Compile.DependentUpon:
    Compile.DependentUpon: Form1.cs
    Compile.DependentUpon: Resources.resx
    Compile.DependentUpon: Settings.settings
    

請注意 "Compile.DependentUpon" 一詞多次出現的方式。Notice how the phrase "Compile.DependentUpon" appears several times. 在目標內搭配此語法使用中繼資料,會導致「批次處理」。The use of metadata with this syntax within a target causes "batching". 批次處理表示會針對每個唯一的中繼資料值執行一次目標內的工作。Batching means that the tasks within the target are executed once for each unique metadata value. 這是相當於「for 迴圈」的一般程式設計建構的 MSBuild 指令碼。This is the MSBuild script equivalent of the common "for loop" programming construct. 如需詳細資訊,請參閱批次處理For more information, see Batching.

已知的中繼資料Well-known metadata

每次將項目加入至項目清單時,即會為該項目指派一些已知的中繼資料。Whenever an item is added to an item list, that item is assigned some well-known metadata. 例如,%(Filename) 會傳回任何項目的檔案名稱。For example, %(Filename) returns the file name of any item. 如需已知中繼資料的完整清單,請參閱已知的項目中繼資料For a complete list of well-known metadata, see Well-known item metadata.

檢查已知的中繼資料To examine well-known metadata

  1. 從程式碼編輯器,使用下列這一行來取代 Message 工作:From the code editor, replace the Message task with this line:

    <Message Text="Compile Filename: %(Compile.Filename)" />
    
  2. 儲存專案檔。Save the project file.

  3. 從 [命令視窗],輸入並執行這一行:From the Command Window, enter and execute this line:

    msbuild buildapp.csproj -t:HelloWorld
    
  4. 檢查輸出結果,Examine the output. 您應該會看到下列這幾行:You should see these lines:

    Compile Filename: Form1
    Compile Filename: Form1.Designer
    Compile Filename: Program
    Compile Filename: AssemblyInfo
    Compile Filename: Resources.Designer
    Compile Filename: Settings.Designer
    

藉由比較上述兩個範例,您會發現,儘管 Compile 項目類型中不是每個項目都具有 DependentUpon 中繼資料,但所有項目都具有已知的 Filename 中繼資料。By comparing the two examples above, you can see that while not every item in the Compile item type has DependentUpon metadata, all items have the well-known Filename metadata.

中繼資料轉換Metadata transformations

項目清單可以轉換為新的項目清單。Item lists can be transformed into new item lists. 若要轉換項目清單,請使用下列語法,其中 <ItemType> 是項目類型的名稱,而 <MetadataName> 是中繼資料的名稱:To transform an item list, use the following syntax, where <ItemType> is the name of the item type and <MetadataName> is the name of the metadata:

@(ItemType -> '%(MetadataName)')

例如,您可以使用像是 @(SourceFiles -> '%(Filename).obj') 的運算式,將原始程式檔的項目清單轉換為目的檔集合。For example, an item list of source files can be transformed into a collection of object files using an expression like @(SourceFiles -> '%(Filename).obj'). 如需詳細資訊,請參閱轉換For more information, see Transforms.

使用中繼資料轉換項目To transform items using metadata

  1. 從程式碼編輯器,使用下列這一行來取代 Message 工作:From the code editor, replace the Message task with this line:

    <Message Text="Backup files: @(Compile->'%(filename).bak')" />
    
  2. 儲存專案檔。Save the project file.

  3. 從 [命令視窗],輸入並執行這一行:From the Command Window, enter and execute this line:

    msbuild buildapp.csproj -t:HelloWorld
    
  4. 檢查輸出結果,Examine the output. 您應該會看到下列這一行:You should see this line:

    Backup files: Form1.bak;Form1.Designer.bak;Program.bak;AssemblyInfo.bak;Resources.Designer.bak;Settings.Designer.bak
    

請注意,此語法中所表示的中繼資料不會導致批次處理。Notice that metadata expressed in this syntax does not cause batching.

後續步驟What's next?

若要了解如何逐步建立簡單的專案檔,請嘗試逐步解說︰從頭建立 MSBuild 專案檔案To learn how to create a simple project file one step at a time, try out the Walkthrough: Creating an MSBuild project file from scratch.

另請參閱See also