19

我想使用 PowerShell 获取我的 csproj 文件中所有项目引用的列表。目前我有以下方法:

[xml]$csproj = Get-Content MyProject.csproj

$refs = $csproj.SelectNodes("//ProjectReference")
foreach($ref in $refs) {
  # Later on output more useful information
  Write-Host $ref.Name
}

但是,该脚本不会输出任何内容,尽管在给定的 csproj 文件中肯定有 ProjectReference 元素。以下是有效的:

[xml]$csproj = Get-Content MyProject.csproj
foreach($l in $csproj.Project.ItemGroup.ProjectReference) { Write-Host $l.Include }

但是我稍后也需要 XPath + 它为每个不包含 ProjectReference 的 ItemGroup 输出错误 - 那么如何使用该SelectNodes函数使 XPath 工作?

示例 XML(基本上任何带有项目引用的 VS csproj 文件都可以):

<?xml version="1.0" encoding="utf-8"?>
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup></ItemGroup>
  <ItemGroup>
     <ProjectReference Include="Text"></ProjectReference>
     <ProjectReference Include="Text2"></ProjectReference>
  </ItemGroup>
  <ItemGroup></ItemGroup>
</Project>
4

1 回答 1

37

问题是http://schemas.microsoft.com/developer/msbuild/2003命名空间。您需要在 XPath 表达式中考虑此命名空间,因为 XPath 中的无前缀元素名称指的是不在命名空间中的元素。

[xml]$csproj = Get-Content MyProject.csproj
$ns = new-object Xml.XmlNamespaceManager $csproj.NameTable
$ns.AddNamespace("msb", "http://schemas.microsoft.com/developer/msbuild/2003")

$refs = $csproj.SelectNodes("//msb:ProjectReference", $ns)
foreach($ref in $refs) {
  # Later on output more useful information
  Write-Host $ref.Name
}

(改编自这个答案

于 2014-04-15T13:43:39.027 回答