2011-05-18 150 views
10

我想在Powershell中編輯一些xml。下面是我在做什麼:如何使用Powershell編輯XML?

$path = 'C:\Projects\NuGetTestPackage\NuGetTestPackage' 
$projName = 'NuGetTestPackage1.csproj' 
cd $path 
$file = gi $projName 
$pattern = 'TextTemplatingFileGenerator' 
$xml = [xml](gc $file) 
$node = [xml] $xml.Project.ItemGroup.None.Generator | 
    Where { $_.Project.ItemGroup.None.Generator -eq $pattern } | 
    Foreach {$_.Project.ItemGroup.None.Generator = ''} 
$xml.Save($file.Fullname) 

這裏的XML:

<?xml version="1.0" encoding="utf-8"?> 
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> 
    <PropertyGroup> 
    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration> 
    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform> 
    <ProductVersion> 
    </ProductVersion> 
    <SchemaVersion>2.0</SchemaVersion> 
    <ProjectGuid>{E750ACF1-17B5-4D83-8FC8-5A4488193099}</ProjectGuid> 
    <ProjectTypeGuids>{E53F8FEA-EAE0-44A6-8774-FFD645390401};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids> 
    <OutputType>Library</OutputType> 
    <AppDesignerFolder>Properties</AppDesignerFolder> 
    <RootNamespace>NuGetTestPackage</RootNamespace> 
    <AssemblyName>NuGetTestPackage</AssemblyName> 
    <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> 
    <MvcBuildViews>false</MvcBuildViews> 
    <UseIISExpress>false</UseIISExpress> 
    </PropertyGroup> 
    <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' "> 
    <DebugSymbols>true</DebugSymbols> 
    <DebugType>full</DebugType> 
    <Optimize>false</Optimize> 
    <OutputPath>bin\</OutputPath> 
    <DefineConstants>DEBUG;TRACE</DefineConstants> 
    <ErrorReport>prompt</ErrorReport> 
    <WarningLevel>4</WarningLevel> 
    </PropertyGroup> 
    <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' "> 
    <DebugType>pdbonly</DebugType> 
    <Optimize>true</Optimize> 
    <OutputPath>bin\</OutputPath> 
    <DefineConstants>TRACE</DefineConstants> 
    <ErrorReport>prompt</ErrorReport> 
    <WarningLevel>4</WarningLevel> 
    </PropertyGroup> 
    <ItemGroup> 
    <Reference Include="EntityFramework, Version=4.1.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089, processorArchitecture=MSIL"> 
     <Private>True</Private> 
     <HintPath>..\packages\EntityFramework.4.1.10331.0\lib\EntityFramework.dll</HintPath> 
    </Reference> 
    <Reference Include="System.Data.Entity" /> 
    <Reference Include="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" /> 
    <Reference Include="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" /> 
    <Reference Include="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" /> 
    <Reference Include="Microsoft.CSharp" /> 
    <Reference Include="System" /> 
    <Reference Include="System.Data" /> 
    <Reference Include="System.Drawing" /> 
    <Reference Include="System.Web.DynamicData" /> 
    <Reference Include="System.Web.Entity" /> 
    <Reference Include="System.Web.ApplicationServices" /> 
    <Reference Include="System.ComponentModel.DataAnnotations" /> 
    <Reference Include="System.Core" /> 
    <Reference Include="System.Data.DataSetExtensions" /> 
    <Reference Include="System.Xml.Linq" /> 
    <Reference Include="System.Web" /> 
    <Reference Include="System.Web.Extensions" /> 
    <Reference Include="System.Web.Abstractions" /> 
    <Reference Include="System.Web.Routing" /> 
    <Reference Include="System.Xml" /> 
    <Reference Include="System.Configuration" /> 
    <Reference Include="System.Web.Services" /> 
    <Reference Include="System.EnterpriseServices" /> 
    </ItemGroup> 
    <ItemGroup> 
    <Compile Include="Application\ApplicationConfigurationSettings.cs" /> 
    <Compile Include="Global.asax.cs"> 
     <DependentUpon>Global.asax</DependentUpon> 
    </Compile> 
    <Compile Include="Properties\AssemblyInfo.cs" /> 
    </ItemGroup> 
    <ItemGroup> 
    <Content Include="Content\themes\base\images\ui-bg_flat_0_aaaaaa_40x100.png" /> 
    <Content Include="Content\themes\base\images\ui-bg_flat_75_ffffff_40x100.png" /> 
    <Content Include="Content\themes\base\images\ui-bg_glass_55_fbf9ee_1x400.png" /> 
    <Content Include="Content\themes\base\images\ui-bg_glass_65_ffffff_1x400.png" /> 
    <Content Include="Content\themes\base\images\ui-bg_glass_75_dadada_1x400.png" /> 
    <Content Include="Content\themes\base\images\ui-bg_glass_75_e6e6e6_1x400.png" /> 
    <Content Include="Content\themes\base\images\ui-bg_glass_95_fef1ec_1x400.png" /> 
    <Content Include="Content\themes\base\images\ui-bg_highlight-soft_75_cccccc_1x100.png" /> 
    <Content Include="Content\themes\base\images\ui-icons_222222_256x240.png" /> 
    <Content Include="Content\themes\base\images\ui-icons_2e83ff_256x240.png" /> 
    <Content Include="Content\themes\base\images\ui-icons_454545_256x240.png" /> 
    <Content Include="Content\themes\base\images\ui-icons_888888_256x240.png" /> 
    <Content Include="Content\themes\base\images\ui-icons_cd0a0a_256x240.png" /> 
    <Content Include="Content\themes\base\jquery.ui.accordion.css" /> 
    <Content Include="Content\themes\base\jquery.ui.all.css" /> 
    <Content Include="Content\themes\base\jquery.ui.autocomplete.css" /> 
    <Content Include="Content\themes\base\jquery.ui.base.css" /> 
    <Content Include="Content\themes\base\jquery.ui.button.css" /> 
    <Content Include="Content\themes\base\jquery.ui.core.css" /> 
    <Content Include="Content\themes\base\jquery.ui.datepicker.css" /> 
    <Content Include="Content\themes\base\jquery.ui.dialog.css" /> 
    <Content Include="Content\themes\base\jquery.ui.progressbar.css" /> 
    <Content Include="Content\themes\base\jquery.ui.resizable.css" /> 
    <Content Include="Content\themes\base\jquery.ui.selectable.css" /> 
    <Content Include="Content\themes\base\jquery.ui.slider.css" /> 
    <Content Include="Content\themes\base\jquery.ui.tabs.css" /> 
    <Content Include="Content\themes\base\jquery.ui.theme.css" /> 
    <Content Include="Global.asax" /> 
    <Content Include="Content\Site.css" /> 
    <Content Include="Scripts\jquery-1.5.1-vsdoc.js" /> 
    <Content Include="Scripts\jquery-1.5.1.js" /> 
    <Content Include="Scripts\jquery-1.5.1.min.js" /> 
    <Content Include="Scripts\jquery-ui-1.8.11.js" /> 
    <Content Include="Scripts\jquery-ui-1.8.11.min.js" /> 
    <Content Include="Scripts\jquery.validate-vsdoc.js" /> 
    <Content Include="Scripts\jquery.validate.js" /> 
    <Content Include="Scripts\jquery.validate.min.js" /> 
    <Content Include="Scripts\modernizr-1.7.js" /> 
    <Content Include="Scripts\modernizr-1.7.min.js" /> 
    <Content Include="T4\WebConfigSettingGeneratorScript.txt"> 
     <AutoGen>True</AutoGen> 
     <DesignTime>True</DesignTime> 
     <DependentUpon>WebConfigSettingGeneratorScript.tt</DependentUpon> 
    </Content> 
    <Content Include="T4\WebConfigSettingGeneratorScript1.txt" /> 
    <Content Include="Web.config" /> 
    <Content Include="Web.Debug.config"> 
     <DependentUpon>Web.config</DependentUpon> 
    </Content> 
    <Content Include="Web.Release.config"> 
     <DependentUpon>Web.config</DependentUpon> 
    </Content> 
    <Content Include="Scripts\jquery.unobtrusive-ajax.js" /> 
    <Content Include="Scripts\jquery.unobtrusive-ajax.min.js" /> 
    <Content Include="Scripts\jquery.validate.unobtrusive.js" /> 
    <Content Include="Scripts\jquery.validate.unobtrusive.min.js" /> 
    <Content Include="Scripts\MicrosoftAjax.js" /> 
    <Content Include="Scripts\MicrosoftAjax.debug.js" /> 
    <Content Include="Scripts\MicrosoftMvcAjax.js" /> 
    <Content Include="Scripts\MicrosoftMvcAjax.debug.js" /> 
    <Content Include="Scripts\MicrosoftMvcValidation.js" /> 
    <Content Include="Scripts\MicrosoftMvcValidation.debug.js" /> 
    <Content Include="Views\Web.config" /> 
    <Content Include="Views\_ViewStart.cshtml" /> 
    <Content Include="Views\Shared\Error.cshtml" /> 
    <Content Include="Views\Shared\_Layout.cshtml" /> 
    </ItemGroup> 
    <ItemGroup> 
    <Folder Include="Controllers\" /> 
    <Folder Include="Models\" /> 
    </ItemGroup> 
    <ItemGroup> 
    <Content Include="packages.config" /> 
    </ItemGroup> 
    <ItemGroup> 
    <None Include="CodeTemplates\AddController\Controller.tt" /> 
    <None Include="CodeTemplates\AddController\ControllerWithContext.tt" /> 
    <None Include="CodeTemplates\AddView\CSHTML\Create.tt" /> 
    <None Include="CodeTemplates\AddView\CSHTML\Delete.tt" /> 
    <None Include="CodeTemplates\AddView\CSHTML\Details.tt" /> 
    <None Include="CodeTemplates\AddView\CSHTML\Edit.tt" /> 
    <None Include="CodeTemplates\AddView\CSHTML\Empty.tt" /> 
    <None Include="CodeTemplates\AddView\CSHTML\List.tt" /> 
    <None Include="T4\Generators\WebConfigGenerator.tt" /> 
    <None Include="T4\Templates\WebConfigTemplate.tt" /> 
    <None Include="T4\WebConfigSettingGeneratorScript.tt"> 
     <Generator>TextTemplatingFileGenerator</Generator> 
     <LastGenOutput>WebConfigSettingGeneratorScript.txt</LastGenOutput> 
    </None> 
    <None Include="T4\WebConfigSettingGeneratorScript.tt.log"> 
     <DependentUpon>WebConfigSettingGeneratorScript.tt</DependentUpon> 
    </None> 
    </ItemGroup> 
    <ItemGroup> 
    <Service Include="{508349B6-6B84-4DF5-91F0-309BEEBAD82D}" /> 
    </ItemGroup> 
    <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> 
    <Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" /> 
    <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
    Other similar extension points exist, see Microsoft.Common.targets. 
    <Target Name="BeforeBuild"> 
    </Target> 
    <Target Name="AfterBuild"> 
    </Target> --> 
    <Target Name="MvcBuildViews" AfterTargets="AfterBuild" Condition="'$(MvcBuildViews)'=='true'"> 
    <AspNetCompiler VirtualPath="temp" PhysicalPath="$(WebProjectOutputDir)" /> 
    </Target> 
    <ProjectExtensions> 
    <VisualStudio> 
     <FlavorProperties GUID="{349c5851-65df-11da-9384-00065b846f21}"> 
     <WebProjectProperties> 
      <UseIIS>False</UseIIS> 
      <AutoAssignPort>True</AutoAssignPort> 
      <DevelopmentServerPort>55059</DevelopmentServerPort> 
      <DevelopmentServerVPath>/</DevelopmentServerVPath> 
      <IISUrl> 
      </IISUrl> 
      <NTLMAuthentication>False</NTLMAuthentication> 
      <UseCustomServer>False</UseCustomServer> 
      <CustomServerUrl> 
      </CustomServerUrl> 
      <SaveServerSettingsInUserFile>False</SaveServerSettingsInUserFile> 
     </WebProjectProperties> 
     </FlavorProperties> 
    </VisualStudio> 
    </ProjectExtensions> 
</Project> 

這樣做是爲了清除發電機節點的值。我似乎無法獲得此代碼的工作。我是否正確訪問xml屬性?這似乎是我爲每個人都獲得了價值,但我無法正確訪問它。


好的,謝謝@Keith Hill。這裏的答案:

$path = 'C:\Projects\NuGetTestPackage\NuGetTestPackage' 
$ns = @{msb = 'http://schemas.microsoft.com/developer/msbuild/2003'} 
cd $path 
$results = 0 
$projName = 'NuGetTestPackage1.csproj' 
$file = gi $projName 
$xml = [xml](gc $projName) 
$xml | Select-Xml "//msb:Generator" -Namespace $ns | 
     Foreach { 
      $_.Node.set_InnerText('') 
      $results = 1 
     } 
if($results -eq 1){ 
    $xml.Save($file.FullName) 
} 
+0

您忘記了「模式」字符串嗎?我不明白這是如何工作的,因爲是? – D3vtr0n 2011-05-23 15:36:39

+2

我很想看到細節和答案一樣通用作爲這個問題的標題。 – 2011-09-22 15:38:24

回答

13

發生這種情況,因爲你有多個「ItemGroup」元素和多個「None」元素。此時,ItemGroup是一個集合,沒有「.None」屬性。您最好使用XPath IMO例如:

$ns = @{msb = 'http://schemas.microsoft.com/developer/msbuild/2003'} 
$pattern = 'TextTemplatingFileGenerator' 
$xml = [xml](gc C:\temp\test.csproj) 
$xml | Select-Xml "//msb:Generator[text() = $pattern]" -Namespace $ns | 
     Foreach {$_.Node.set_InnerText('')} 
$xml.Save('C:\temp\test.csproj') 
+0

我不反對。但是,當我嘗試過,我最終與NADA結束。即使在測試你的代碼時,我看到的仍然是NADA。有任何想法嗎? – 2011-05-18 20:52:56

+0

好的,更多信息。如果我說Foreach {$ _。Node.InnerText},那麼我會得到正確的值。這個問題似乎是在設定價值。 – 2011-05-18 20:57:14

+1

嗯,它適用於我給你上面提供的C#項目文件(PowerShell 2.0)。你可以嘗試使用'__。Node.set_InnerText('')'來查看是否有效。順便說一句,定義你的意思是「結束與NADA」?更新的C#項目文件中沒有任何內容? – 2011-05-18 21:21:07

3

我真的不明白你的問題

$file = get-item "c:\Yourfile.xml" 

$xml = [xml](get-content $file) 

$xml.Project.ItemGroup.None.Generator = "" 

$xml.Save("c:\YourModifiedFile.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> 
    </ItemGroup> 
</Project> 
+0

這會產生一個錯誤。不是嗎? - 在此對象上找不到「發電機」屬性;確保它存在並可設置。 – 2011-05-18 19:33:41

+0

嗯...我減少了我的XML只是我提供給你,現在它的工作原理。也許我有這個問題,因爲我的XML非常複雜? – 2011-05-18 19:35:01