2011-05-17 64 views
9

我正在解析nuget安裝的csproj文件,並且我有一個需要修改的節點。所討論的節點是名爲「Generator」的節點,其值等於「TextTemplatingFileGenerator」,並且其父節點具有「WebConfigSettingsGeneratorScript.tt」(第二部分尚未在此處)的屬性。PowerShell解析xml並保存更改

這是我得到的腳本,但它沒有完成。它正在工作,但它保存了一個空文件。此外,它沒有我的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!

回答

20

由於@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) 
+0

這會有所幫助,但$ xml.Save($ file.FullName)快到了是無效操作。 – 2011-05-18 13:41:52

+1

如果相應的XmlDocument格式不正確,則記錄XmlDocument.Save(string path)唯一的異常是XmlException。順便說一句,你還應該拋棄'Set-Content $ file.FullName $ xml',因爲'$ xml.Save($ file.Fullname)'調用會保存在原始文件中。 – 2011-05-18 15:32:28

+0

太好了,我已經採取了您提供的更改。但是,它似乎沒有對文件進行更改。但是,該腳本正在保存該文件。 – 2011-05-18 16:08:28

5

你是否缺少演員?

 
$xml = [xml] gc $file.FullName