晚上好!我试图使用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

我意识到自己可能会考虑这个问题,但是对于我自己的一生,我无法弄清楚自己在做什么错。任何人都可以简化吗?

最佳答案

这是$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"
    }
}

10-07 17:57