【问题标题】:Editing XML Attributes using Powershell使用 Powershell 编辑 XML 属性
【发布时间】:2014-09-12 00:45:37
【问题描述】:

所以我有一个 .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 下的属性 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

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

【问题讨论】:

  • 如果你展示你尝试过的代码,有人可能会指出那里出了什么问题。我想这会更有帮助。

标签: powershell


【解决方案1】:

有很多方法。例如,您可以使用 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

更多信息here 和 w3schools.com 通常是您处理 HTML 或 XML 的朋友。

【讨论】:

  • 非常感谢,确实有效!我唯一改变的部分是 $XML.OUTerXML | Out-File $FileLocation to $XML.Save($FileLocation) 只是为了保持文件的格式,当我查看文件以验证更改时。星期五和今天早上我整天都在为此苦苦挣扎,所以谢谢你的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-28
  • 1970-01-01
  • 1970-01-01
  • 2023-04-07
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多