【问题标题】:Update config file contents with output from Active Directory query使用 Active Directory 查询的输出更新配置文件内容
【发布时间】:2020-04-19 08:33:26
【问题描述】:

Powershell 新手在这里!我需要一些帮助来替换我的配置文件中的值以匹配 Active Directory 中用户扩展属性的值。

这是我所拥有的:

$XML = "C:\Users\Test.User04\Documents\test.config"

$Variable = Get-ADUser -Identity $env:username -prop othertelephone -Server generic.com.au |选择@{n="othertelephone";e={$_.othertelephone -join ";"}}

(获取内容 $XML | Foreach 对象 {$_ -replace '10586',"$Variable"} | 设置内容 C:\Users\Test.User04\Documents\test2.config)

问题:

  1. 当我只需要值时,来自 AD 扩展属性的查询提供名称和值

  2. 如何精确定位配置文件中的特定位置(屏幕截图中的红框),仅需要用扩展属性值替换。

如您所见,上述代码的当前限制是我必须在配置文件中手动指定值,在本例中为“10586”。我想要做的是始终替换配置文件中的值,无论数字是多少。 Screenshot of config file with red box around value requiring replacement

【问题讨论】:

  • [1] 为什么不将加载的 XML 文本转换为 XML object?这将允许您访问和修改各种项目作为道具,然后将结果导出为 XML 文本文件。 [2] 由于您发布了 XML 文件的图片,因此没有人可以使用该数据来测试代码。 [叹息...]
  • 我将研究 XML 对象。我是该站点的新手,并注意到您无法附加文件。感谢您的及时回复。
  • 是的...您不能附加文件。如果您需要使用一个太大而无法粘贴到问题中的文件,那么您可能需要将文件修剪到一个可行的大小。

标签: xml powershell


【解决方案1】:

Lee_Daily 是正确的,您不应该在 xml 文件上使用正则表达式替换。 PowerShell 让处理 xml 变得非常容易。

由于您没有提供具有代表性的 textual xml 示例,因此未经测试:

$xmlOut   = 'C:\Users\Test.User04\Documents\test2.config'
[xml]$xml = Get-Content -Path 'C:\Users\Test.User04\Documents\test.config' -Raw

# $Variable will be an object with one property 'otherTelephone'
$Variable = Get-ADUser -Identity $env:username -Properties otherTelephone -Server 'generic.com.au' | 
            Select-Object @{Name = "otherTelephone"; Expression = {$_.otherTelephone -join ";"}}

# find the node for which you need to replace the 'user' attribute
$userNode = $xml.SipEndpoint.Container.Connectivity | Where-Object { $_.user -eq '10586' }

# if found, replace the attribute with the 'otherTelephone' property in $Variable
if ($userNode) { $userNode.SetAttribute('user', $Variable.otherTelephone) }

# save the updated xml as new file
$xml.Save($xmlOut)

【讨论】:

  • 非常感谢西奥和李。上面的脚本解决了我的第一个问题,它只更新了所需的值!我有一个解决我的第二个问题的方法。感谢您深厚的知识和帮助:) 我一直在玩 XML 对象,现在有了更好的理解。
猜你喜欢
  • 2019-08-17
  • 2023-03-18
  • 2010-11-08
  • 2020-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-26
相关资源
最近更新 更多