PowerShell解析xml并保存更改

Don*_*ing 10 xml powershell

我正在解析一个用于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
    }   
}
Run Code Online (Sandbox Code Playgroud)

这是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>
Run Code Online (Sandbox Code Playgroud)

非常感谢.我是一个完整的PowerShell n00b!

Kei*_*ill 26

正如@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)
Run Code Online (Sandbox Code Playgroud)

  • 这有帮助,但 $xml.Save($file.FullName) 将作为无效操作出现。 (2认同)

Emi*_*ggi 5

你错过了演员吗?

$xml = [xml] gc $file.FullName