11

我正在解析一个用于 nuget 安装的 csproj 文件,并且我有一个需要更改的节点。有问题的节点是名为“Generator”的节点,它的值等于“TextTemplatingFileGenerator”,它的父节点具有“WebConfigSettingsGeneratorScript.tt”的属性(第二部分还没有在这里)。

这是我得到的脚本,但还没有完成。它正在工作,但它保存了一个空文件。此外,它没有我的 where 子句的第二部分,即

$path = 'C:\Projects\Intouch\NuGetTestPackage\NuGetTestPackage'
cd $path
$files = get-childitem -recurse -filter *.csproj
foreach ($file in $files){
    ""
    "Filename: {0}" -f $($file.Name)
    "=" * ($($file.FullName.Length) + 10)   

    if($file.Name -eq 'NuGetTestPackage1.csproj'){
        $xml = gc $file.FullName | 
        Where-Object { $_.Project.ItemGroup.None.Generator -eq 'TextTemplatingFileGenerator' } | 
        ForEach-Object { $_.Project.ItemGroup.None.Generator = '' }
        Set-Content $file.FullName $xml
    }   
}

这是 XML 的基本版本:

<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ItemGroup>
    <None Include="T4\WebConfigSettingGeneratorScript.tt">
      <Generator>TextTemplatingFileGenerator</Generator>
      <LastGenOutput>WebConfigSettingGeneratorScript.txt</LastGenOutput>
    </None>

非常感谢。我是个 PowerShell n00b!

4

3 回答 3

30

正如@empo 所说,您需要将输出gc $file.FullName转换为 [xml] 例如$xml = [xml](gc $file.FullName)。然后在进行更改之后但在循环到下一个文件之前,您需要保存文件,例如$xml.Save($file.FullName).

这适用于您提供的示例项目:

$file = gi .\test.csproj
$pattern = 'TextTemplatingFileGenerator'
$xml = [xml](gc $file)
$xml | Where {$_.Project.ItemGroup.None.Generator -eq $pattern} |
       Foreach {$_.Project.ItemGroup.None.Generator = ''}
$xml.Save($file.Fullname)
于 2011-05-17T23:11:18.130 回答
5

你缺演员吗?

$xml = [xml] gc $file.FullName
于 2011-05-17T22:44:52.473 回答
0

好的,现在我的更改正在起作用:

    $fileName = “C:\sovgarde\updates.xml”;
$xml = [System.Xml.XmlDocument](Get-Content $fileName);

$child = $xml.CreateElement('option')
$child.SetAttribute('name', 'CHECK_NEEDED')
$child.SetAttribute('value','false')
If ($xml.application.component.option.name -icontains "CHECK_NEEDED") {
    
    $xml.SelectNodes("//option[@name=`"CHECK_NEEDED`"]") | % {$_.ParentNode.removechild($_) }
    #$xml.Save($fileName)   
    
}
$node = $xml.SelectSingleNode('//component')
$node.AppendChild($child)
$xml.Save($fileName)
于 2020-11-26T20:46:41.137 回答