gpt4 book ai didi

xml - PowerShell - 格式化 XML 输出

转载 作者:数据小太阳 更新时间:2023-10-29 02:06:20 28 4
gpt4 key购买 nike

晚上好!我正在尝试使用 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"
}
}

关于xml - PowerShell - 格式化 XML 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25027403/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com