【问题标题】:Read xml file and store the key value in hashtable using powershell使用powershell读取xml文件并将键值存储在哈希表中
【发布时间】:2021-09-28 08:41:31
【问题描述】:

我需要读取下面的 xml 文件并将其存储在哈希表中。

<?xml version="1.0"?>
<ConfigValues>
   <Dev>
     <item Key="dbconn" Value ="Data Source=xlvxdev.cumulus.com,1615;Initial Catalog=FPTR_XLVX;Security=true;"/>
   </Dev>
   <QA>
     <item Key="dbconn" Value ="Data Source=xlvxqa.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;"/>
   </QA>
   <PP>
     <item Key="dbconn" Value ="Data Source=xlvxpreprd.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;"/>
   </PP>
   <PROD>
     <item Key="dbconn" Value ="Data Source=xlvxprd.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;"/>
   </PROD>
</ConfigValues>

我尝试在 powershell 下编写并能够获取属性键值,但我需要将其存储在哈希表中,以便我可以根据需要检索值。

$URLS = [xml](Get-Content 'C:\Desktop\Variables.xml')

$URLS.ConfigValues.Dev.item | where {$_.key -eq 'connCVRC'}
Key      Value
---      -----
connCVRC Data Source=xlvxdev.cumulus.com,1615;Initial Catalog=FPTR_XLVX;Security=true;

【问题讨论】:

  • 不太清楚你想要什么作为输出,是$xml.ConfigValues.Dev.Item.Value.Split(';') | ConvertFrom-StringData吗?请在您的问题中添加预期结果。
  • 感谢您与我联系。我正在寻找 mklement0 在以下答案中提供的相同结果

标签: powershell hashtable


【解决方案1】:
# Parse the XML file into an XML DOM
($xml = [xml]::new()).Load((Convert-Path C:\Desktop\Variables.xml))

# Initialize the (ordered) output hashtable.
$hash = [ordered] @{}

# Populate the hashtable with the <ConfigValues> child element 
# names as the key, and their <item> child's Value attribute as the value.
$xml.ConfigValues.ChildNodes.ForEach({
   $hash[$_.Name] = $_.item.Value
})

$hash # output

以上产出:

Name                           Value
----                           -----
Dev                            Data Source=xlvxdev.cumulus.com,1615;Initial Catalog=FPTR_XLVX;Security=true;
QA                             Data Source=xlvxqa.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;
PP                             Data Source=xlvxpreprd.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;
PROD                           Data Source=xlvxprd.cumulus.com,1615;Initial Catalog=OPSR_CVRC;Security=true;

【讨论】:

  • 我很高兴,@pandeg87。听起来这个答案可以解决您的问题,但根据您的评论,我不确定。无论哪种方式,请允许我在下一条评论中给新人标准的建议:
  • 如果您accept 回答,您将通过向他们展示解决您的问题的方法来帮助未来的读者。要接受答案,请单击答案左侧大数字下方的大 ✓ 符号(您将获得 2 点声望)。如果您至少有 15 个声望点,您还可以对其他有用的答案进行投票(也可以选择已接受的答案)。如果您的问题尚未解决,请提供反馈,或者,如果您自己找到了解决方案,请self-answer
猜你喜欢
  • 2021-03-02
  • 1970-01-01
  • 1970-01-01
  • 2012-09-06
  • 2012-02-01
  • 1970-01-01
  • 2017-09-09
  • 1970-01-01
  • 2021-01-22
相关资源
最近更新 更多