使用Powershell编辑XML属性

7

我有一个.exe.config文件,想要在其中搜索特定的属性,并使用Windows 7中的PowerShell版本4.0进行编辑,但遇到了问题。我尝试了几种方法,但都没有成功。以下是我正在使用的配置文件的简化版本。

<configuration>
  <Config1>
    <section name="text" type="text, text, text=text" allowLocation="true" allowDefinition="Everywhere" allowExeDefinition="MachineToApplication" restartOnExternalChanges="true" requirePermission="true" />
  </Config1>
  <Config2>
    <module debugLogLevel="Debug" Version="1.0.0.0" />
    <Interested-Item attribute-1="text-text" attribute2="0">
    </Interested-Item>
    <modules>
      <add name="something1" />
      <add name="something2" />
      <add name="something3" />
      <add name="something4" />
      <add name="something5" />
      <add name="something6" />
      <add name="something7" />
    </modules>
  </Config2>        
</configuration>

我该如何使用PowerShell更改Interested-Item下的attribute-1属性?非常感谢您的帮助。
以下是我曾经尝试但未成功的几个示例。
$File = Get-Content $FileLocation
$XML = [XML]$File

foreach ($attribute in $XML.Config2.Interested-Item)
{
     $attribute = Interested-Item.attribute-1 = "Updated Texted"
}
XML.Save($FileLocation)

这对我毫无帮助。它根本没有编辑文件。
$File = Get-Content $FileLocation
$node = $File.SelectSingleNode("/Config2/Interetested-Item[@attribute-1]")
$node.Value = "New-Value"
$File.Save($FileLocation)

这会返回以下错误。
The property 'Value' cannot be found on this object. Verify that the property exists and can be set.At line:5 char:1
+ $node.Value = "New-Value"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound

我尝试使用从Get-Help Select-XML中获得的-Xpath来实现它,但也没有成功。

唯一有效但实际上不适用的方法是以下内容:

(Get-Content $FileLocation) | ForEach-Object{$_ -replace "text-*", "NewText"} | Set-Content $FileLocation

这将强制第一次运行,然后由于设置了新值,之后将无法更新参数。我的目的是多次运行此脚本以更新一组配置文件。


2
如果您展示您尝试过的代码,有人可能会指出哪里出了问题。我想这会更有帮助。 - anderas
1个回答

5
有许多方法。例如,您可以使用XPath:
$File = Get-Content $FileLocation
$XML = [XML]$File

$XPpath = "/configuration/Config2/Interested-Item[@attribute-1]"

# Selecting all nodes that match our $XPath (i.e. all
# '/configuration/Config2/Interested-Item' nodes that have attribute 
# 'attribute-1'.
$nodes = $XML.SelectNodes($XPpath)

# Updating the attribute value for all selected nodes.
$nodes | % { $_.SetAttribute("attribute-1", "foo") }

$XML.OuterXml | Out-File $FileLocation

更多信息可以在这里查看,通常情况下,当您处理HTML或XML时,w3schools.com是您的朋友。

非常感谢,这确实有效!我所更改的仅有部分是将$XML.OUterXML | Out-File $FileLocation更改为$XML.Save($FileLocation),以保留文件的格式,以便我查看文件以验证更改。我在周五和今天早上一整天都在苦苦挣扎,所以感谢您的帮助! - micsea64

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