PowerShell XML SelectNodes无法处理XPath

PowerShell XML SelectNodes无法处理XPath,xml,powershell,xpath,powershell-4.0,Xml,Powershell,Xpath,Powershell 4.0,我想使用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 } 但是,脚本不会输出任何内容,尽

我想使用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+它为每个不包含项目引用的项目组输出错误-那么如何使用
SelectNodes
函数使XPath工作呢

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



问题在于
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
}

(改编自)

您能否添加一个提供所述行为的示例XML文档?
[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
}