當您想要自訂在特定電腦、虛擬機器或容器上執行的所有組建時,本文中的技術很有用。 例如,當您設定組建伺服器時,您可能需要為伺服器上的所有組建全域設定 MSBuild 設定。 原則上,您可以修改全域 Microsoft.Common.Targets 或 Microsoft.Common.Props 檔案,但有更好的方法。 您可以使用特定 MSBuild 屬性,並新增特定自訂 .targets 和 .props 檔案,以影響特定專案類型的所有組建 (,例如所有 C# 專案)。
標準 .props 和 .targets 檔案之前和之後
若要影響 MSBuild 或 Visual Studio 安裝所控管的所有 C# 或 Visual Basic 組建,請建立檔案 Custom.Before.Microsoft.Common.Targets 或 Custom.After.Microsoft.Common.Targets ,其目標將在 Microsoft.Common.targets 之前或之後執行,或檔案 Custom.Before.Microsoft.Common.Props 或 Custom.After.Microsoft.Common.Props ,其屬性將在 Microsoft.Common.props 之前或之後處理。
您可以使用下列 MSBuild 屬性來指定這些檔案的位置:
- CustomBeforeMicrosoftCommonProps
- CustomBeforeMicrosoftCommonTargets
- CustomAfterMicrosoftCommonProps
- CustomAfterMicrosoftCommonTargets
- CustomBeforeMicrosoftCSharpTargets
- CustomBeforeMicrosoftVisualBasicTargets
- CustomAfterMicrosoftCSharpTargets
- CustomAfterMicrosoftVisualBasicTargets
這些屬性的 Common 版本會影響 C# 和 Visual Basic 專案。 您可以在 MSBuild 命令列中設定這些屬性。
msbuild /p:CustomBeforeMicrosoftCommonTargets="C:\build\config\Custom.Before.Microsoft.Common.Targets" MyProject.csproj
警告
如果 Visual Studio 在 MSBuild 資料夾中找到相符類型專案的自訂 .targets 或 .props 檔案,則在建置時會使用這些檔案。 此自定義可能會產生非預期的後果,如果操作不正確,可能會禁用 Visual Studio 在您的計算機上構建的能力。
替換通用道具檔案
您也可以使用屬性 AlternateCommonProps 來指定要使用的您自己的 .props 檔案,而不是 Microsoft.Common.props。 如果您覺得需要直接修改 Microsoft.Common.props ,您可以改為將該檔案的標準版本複製到另一個檔案中,然後只在替代版本中進行變更。
最佳方法取決於您的案例。 使用 Visual Studio 擴充性,您可以自訂建置系統,並提供安裝和管理自訂的機制。
如果您有專用的組建伺服器,且想要確保某些目標一律在該伺服器上執行之適當專案類型的所有組建上執行,則使用全域自訂 .targets 或 .props 檔案是有意義的。 如果您想要自訂目標只在特定條件套用時執行,請使用另一個檔案位置,並僅在需要時在 MSBuild 命令列中設定適當的 MSBuild 屬性來設定該檔案的路徑。
相關內容
- 自訂設置。