How do I use Powershell to add/remove references to a csproj?

I think the problem is that your XML file has a default namespace xmlns="http://schemas.microsoft.com/developer/msbuild/2003". This causes problems with XPath. So you XPath //ProjectReference will return 0 nodes. There are two ways to solve this:

  1. Use a namespace manager.
  2. Use namespace agnostic XPath.

Here’s is how you could use a namespace manager:

$nsmgr = New-Object System.Xml.XmlNamespaceManager -ArgumentList $proj.NameTable
$nsmgr.AddNamespace('a','http://schemas.microsoft.com/developer/msbuild/2003')
$nodes = $proj.SelectNodes('//a:ProjectReference', $nsmgr)

Or:

Select-Xml '//a:ProjectReference' -Namespace $nsmgr

Here’s how to do it using namespace agnostic XPath:

$nodes = $proj.SelectNodes('//*[local-name()="ProjectReference"]')

Or:

$nodes = Select-Xml '//*[local-name()="ProjectReference"]'

The second approach can be dangerous because if there were more than one namespace it could select the wrong nodes but not it your case.

Leave a Comment