PowerShell - 格式化XML输出

时间:2014-07-30 01:22:51

标签: xml powershell xml-parsing

晚上好!我尝试使用PowerShell读取XML文件,然后以特定方式输出所选节点。我几乎就在那里,但经过大量的研究,我很难过。

请考虑以下事项:

$xml = [xml]@'
<?xml version="1.0" encoding="utf-8"?>
  <registryKeys>
    <registryKey keyName="HKEY_CLASSES_ROOT\CLSID\TestKey1" owner="false">
      <registryValue name="TestValueName1" valueType="REG_EXPAND_SZ" value="TestValue1" operationHint="replace" owner="true" />
      <registryValue name="TestValueName2" valueType="REG_SZ" value="TestValue2"     operationHint="replace" owner="true" />
    </registryKey>
    <registryKey keyName="HKEY_CLASSES_ROOT\CLSID\TestKey2" owner="false">
      <registryValue name="TestValueName3" valueType="REG_EXPAND_SZ" value="TestValue3" operationHint="replace" owner="true" />
      <registryValue name="TestValueName4" valueType="REG_SZ" value="TestValue4" operationHint="replace" owner="true" />
    </registryKey>
  </registryKeys>
'@

$regKeyNode=$xml.SelectNodes("/registryKeys/registryKey")

foreach ($registryKey in $regKeyNode) {
    $keyname = $registrykey.keyName
    $name = $registryKey.registryValue.name
    $value = $registryKey.registryValue.value
    $namevalue =  $name+"="+$value
    Write-Host "Write-Host Line: $keyname"
    Write-Host "Write-Host Line: $namevalue"
}

运行上面的代码后,我收到以下输出:

Write-Host Line:  HKEY_CLASSES_ROOT\CLSID\TestKey1
Write-Host Line:  TestValueName1 TestValueName2 = TestValue1 TestValue2
Write-Host Line:  HKEY_CLASSES_ROOT\CLSID\TestKey2
Write-Host Line:  TestValueName3 TestValueName4 = TestValue3 TestValue4

这不是我希望如何格式化返回的输出。我需要它像这样返回:

Write-Host Line:  HKEY_CLASSES_ROOT\CLSID\TestKey1
Write-Host Line:  TestValueName1 = TestValue1
Write-Host Line:  TestValueName2 = TestValue2
Write-Host Line:  HKEY_CLASSES_ROOT\CLSID\TestKey1
Write-Host Line:  TestValueName3 = TestValue3
Write-Host Line:  TestValueName4 = TestValue4

我意识到我可能在想这个,但对于我的生活,我无法弄清楚我做错了什么。有人能够简化这个吗?

1 个答案:

答案 0 :(得分:4)

这是$regkeynode

的输出
keyName                    owner                      registryValue             
-------                    -----                      -------------            
HKEY_CLASSES_ROOT\CLSID... false                      {TestValueName1, TestV...
HKEY_CLASSES_ROOT\CLSID... false                      {TestValueName3, TestV...

我们在这里可以看到RegistryValue是一个数组并且可以包含多个值,因此当您调用$registrykey.registryvalue.name时,您同时获得每个名称,如果有10个名称,则获得10个名称不是每个人都是单独的。

另一个ForEach应该解决这个问题

首先,我们通过每个$registrykey获取$keyname
然后每个$registryvalue获得$registryvalue.name$registryvalue.value

您可以使用的示例代码

foreach ($registryKey in $regKeyNode)
{
    $keyname = $registrykey.keyName
    Write-Host "Write-Host Line: $keyname"

    foreach ($registryValue in $registryKey.registryValue)
    {
        $name = $registryValue.Name
        $value = $registryValue.value
        $namevalue =  $name+"="+$value
        Write-Host "Write-Host Line: $namevalue"
    }
}