如何使用 PowerShell 读取 MSBuild PropertyGroup 的值?

How can I read the value of an MSBuild PropertyGroup using PowerShell?

我有以下 MSBuild (TestBuild.xml) 文件:

<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  ...
  <Import Project="folderA\A.targets"/>

  <!-- bunch of stuff -->
  <PropertyGroup>    
    <ApplicationName>MyApp</ApplicationName>
    <SolutionName>MySolution</SolutionName>
    <VersionFile>Version.cs</VersionFile>
    <TargetPackageVersion>$(RELEASE_VERSION)</TargetPackageVersion>
    <BuildPlatform Condition=" '$(BuildPlatform)' == '' ">x86</BuildPlatform>
    <TestAssembliesPattern>*Tests*.dll</TestAssembliesPattern>
    ...    
  </PropertyGroup>

  <!-- bunch of more stuff -->
  <PropertyGroup>
    <ConfigurationContentFolder>$(MSBuildProjectDirectory)\Configuration</ConfigurationContentFolder>
    <PluginName>ABC</PluginName>
  </PropertyGroup>
  ...
</Project>

在这种情况下,我希望能够获得 VersionFile 节点的值 Version.cs 我一直在使用 XPath,希望以下内容能够工作:

$xdoc = [xml] $xdoc = get-content ".\TestBuild.xml"
$xdoc.SelectSingleNode("//VersionFile") | select { $_.InnerText }
$xdoc.SelectSingleNode("VersionFile") | select { $_.InnerText }

但到目前为止我还没有任何运气。非常感谢任何帮助。

我认为您需要执行 MSBuild,运行 自定义目标,并捕获结果值。

将 msbuild 项目视为 xml 文件可能无法获得您想要的结果。考虑 属性 是根据配置设置(调试与发布等)动态定义或有条件地计算的情况。

Xml 有一个名称空间,因此您必须限定元素名称。使用 Select-Xml 计算具有命名空间的 XPath:

$xml = [xml](get-content ".\TestBuild.xml")
$ns = @{ msb = "http://schemas.microsoft.com/developer/msbuild/2003" }
Select-Xml $xml -Namespace $ns -XPath "//msb:VersionFile" | foreach { $_.Node.InnerText }