如何使用PowerShell编辑.csproj文件-Visual Studio 2010

8

我需要帮助使用PowerShell编辑csproj文件。基本上,我需要选择一个节点并进行修改。

例如:

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

我需要从这个标签中删除 TextTemplatingFileGenerator 属性。
1个回答

13

我经常这样做。我保留了一组帮助函数,用于操作 XML 文件,特别是 C# 项目文件。请尝试以下代码:

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)

非常感谢。我应该从哪里运行这个?您知道选择当前项目或启动项目的任何方法吗? - Don Rolling
我会把这段代码放到一个 RemoveTTFileGeneratorNode.ps1 文件(PowerShell 脚本文件)中,然后从 PowerShell 提示符中运行它,将 C# 项目文件的路径传递给它。 - Keith Hill
很抱歉不得不问,但在ps提示符下运行它的语法是什么?- 真诚的powershell n00b - Don Rolling
没问题。语法应该是:C:\PS> c:\some_path\RemoveTTFileGeneratorNode.ps1 c:\some_path\foo.csproj - Keith Hill
@KeithHill 刚刚尝试运行这个脚本,但出现了“根级别处的数据无效”的错误。你是不是想调用 RemoveElement $proj 呢?(同时 $proj = [xml](Get-Content $path))。祝好。 - Dr. Andrew Burnett-Thompson
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接