Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Edit .csproj files with PowerShell - Visual Studio 2010

I need some help editing a csproj file using PowerShell. I basically need to select a node and alter it.

Example:

<None Include="T4\WebConfigSettingGeneratorScript.tt">
  <Generator>TextTemplatingFileGenerator</Generator>
  <LastGenOutput>WebConfigSettingGeneratorScript1.txt</LastGenOutput>
</None>

I need to remove the TextTemplatingFileGenerator attribute from this tag.

like image 556
Don Rolling Avatar asked May 17 '11 16:05

Don Rolling


People also ask

How do I edit a .csproj file?

Right-click on the project (tagged as unavailable in solution explorer) and click "Edit yourproj. csproj". This will open up your CSPROJ file for editing. After making the changes you want, save, and close the file.

How do I open a .csproj file?

How to open a CSPROJ file. CSPROJ files are are meant to be opened and edited in Microsoft Visual Studio (Windows, Mac) as part of Visual Studio projects. However, because CSPROJ files are XML files, you can open and edit them in any text or source code editor.

How do I edit Csproj in Visual Studio Mac?

You should be able to do this by right clicking the project in the Solution window and selecting Tools - Edit File. That will open the project file (. csproj) in the text editor.

What is Csproj file?

What is a CSProj file? Files with CSPROJ extension represent a C# project file that contains the list of files included in a project along with the references to system assemblies.


1 Answers

I do this kind of thing a lot. I keep around a set of helper functions for manipulating XML files - particular C# project files. Try this out:

param($path)
$MsbNS = @{msb = 'http://schemas.microsoft.com/developer/msbuild/2003'}

function RemoveElement([xml]$Project, [string]$XPath, [switch]$SingleNode)
{
    $nodes = @(Select-Xml $XPath $Project -Namespace $MsbNS | Foreach {$_.Node})
    if (!$nodes) { Write-Verbose "RemoveElement: XPath $XPath not found" }
    if ($singleNode -and ($nodes.Count -gt 1)) { 
        throw "XPath $XPath found multiple nodes" 
    }
    foreach ($node in $nodes)

        $parentNode = $node.ParentNode
        [void]$parentNode.RemoveChild($node)
    }
}

$proj = [xml](Get-Content $path)
RemoveElement $proj '//msb:None/msb:Generator' -SingleNode
$proj.Save($path)
like image 124
Keith Hill Avatar answered Sep 26 '22 07:09

Keith Hill