通过XML在PowerShell中导入/导入多值注册表项

随你

我在使用PowerShell导出/导入注册表值时遇到一些麻烦,特别是在使用multivalue(REG_MULTI_SZ)键时。我有一个测试注册表项:

[HKEY_CURRENT_USER \ SOFTWARE \ my \ Testkey] 
“ string” =“ blub” 
“ multi” = hex(7):6f,00,6e,00,65,00,00,00,74,00,77,00,6f ,00,00,00,74,00,68,00,72,\ 
  00,65,00,65,00,00,00,00,00 
“ bin” = hex:11,11,11,11,10

现在,如果我执行以下操作

$Hive = "HKCU:\SOFTWARE\my\Testkey"
$Property = (Get-ItemProperty -path $Hive)
$Property.PSObject.Properties |
    select name, value, TypeNameOfValue |
    Where-Object name -NotLike "PS*" |
    Export-Clixml test.xml
$Prop = Import-Clixml .\test.xml 

foreach ($i in $Prop) {
    New-ItemProperty -Path $Hive -Name $i.Name -Value $i.Value 
}

注册表中键的值设置为"System.Collections.ArrayList"而不是其实际值。它似乎只发生在多值键上。

我试过了

New-ItemProperty -Path $Hive -Name $i.Name -Value ($i.Value | Out-String)

但这也不起作用。似乎New-ItemProperty没有将字符串数组转换为正确的类型。任何人都知道要使用哪种数据类型/如何解决此问题?

显然我可以使用

foreach($i in $Prop){
    if ($i.TypeNameOfValue -eq 'System.String[]') {
        New-ItemProperty -Path $Hive -Name $i.Name -Value $i.Value -PropertyType "MultiString"
    } else {
        New-ItemProperty -Path $Hive -Name $i.Name -Value $i.Value 
    }
}

但我更愿意$i.Value在导入或导入期间将其转换为正确的数据类型。

还是我忽略了其他任何聪明的解决方案?

安斯加·威彻斯(Ansgar Wiechers)

您需要使用正确的类型导入值。创建一个哈希表,将导入的数据的类型映射到相应的注册表数据类型,并在导入时查找类型名称:

$regtypes = @{
    'System.String'   = 'String'
    'System.String[]' = 'MultiString'
    'System.Byte[]'   = 'Binary'
}

foreach ($i in $Prop) {
    New-ItemProperty -Path $Hive -Name $i.Name -Value $i.Value -Type $regtypes[$i.TypeNameOfValue]
}

一种替代方法是将该值转换为导入的类型名称:

foreach ($i in $Prop) {
    New-ItemProperty -Path $Hive -Name $i.Name -Value ($i.Value -as $i.TypeNameOfValue)
}

请注意,通过-Type参数传递导入的类型名称并不适用于所有类型。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章