代码之家  ›  专栏  ›  技术社区  ›  whatever

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

  •  1
  • whatever  · 技术社区  · 8 年前

    我在使用PowerShell执行/导入注册表值时遇到一些问题,特别是在使用多值时( 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 在ex-或import过程中转换为正确的数据类型。

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

    1 回复  |  直到 8 年前
        1
  •  1
  •   Ansgar Wiechers    8 年前

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

    $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 参数执行 不 适用于所有类型。

    推荐文章