PAYATHON 2026

PowerShell 5.1 中重命名名称含正斜杠的注册表键

数据小陈

结论

在 PowerShell 5.1 里,注册表键名如果包含 /,不要用 Rename-Item -NewName 来改。注册表 Provider 会把这个参数当成路径来解析和校验,最后报 The registry key at the specified path does not exist.。可以把键移动到同一父键下,用新名称作为目标,命令是 Move-Item -Destination。如果 Move-Item 不适用,再用 .NET 的 Microsoft.Win32.RegistryKey:新建键,复制值和子键,最后删掉旧键。

原因

注册表键名本身允许出现正斜杠,CreateSubKey、Copy-Item 和 Move-Item 都能正常处理。出问题的是 Rename-Item 的 -NewName。它接收的是叶名称,但 5.1 的实现会把新名称里的 / 当成路径相关字符,最后就找不到目标键了。用反引号转义 / 对 -NewName 没有用。

方案一:用 Move-Item 重命名

目标父键必须已经存在,目标键不能已经存在。示例:

$old = 'HKLM:\SOFTWARE\MySoftware\Path=//Server/UNC/path/goes/here'
$new = 'HKLM:\SOFTWARE\MySoftware\Path=//Server/New/UNC/path/here'

if (Test-Path -LiteralPath $new) {
    throw "目标键已存在:$new"
}

Move-Item -LiteralPath $old -Destination $new -ErrorAction Stop

执行后可以这样检查:

Test-Path -LiteralPath $new
Get-Item -LiteralPath $new

之所以用 -LiteralPath,是因为路径里可能有 Provider 会特殊解释的字符。/ 不是通配符,但用 -LiteralPath 更稳妥。如果只是想先把旧键复制到新名称,再删掉旧键,也可以这样做:

Copy-Item -LiteralPath $old -Destination $new -Recurse -ErrorAction Stop
Remove-Item -LiteralPath $old -Recurse -ErrorAction Stop

不过 Move-Item 更接近真正的重命名,一般优先用它。

方案二:用 .NET Registry API 复制后删除

如果需要精确控制复制过程,或者某个环境里 Move-Item 不适用,可以用 .NET API。下面的示例针对 HKLM 默认视图,会递归复制值和子键。如果要处理 32 位或 64 位视图,把 RegistryView::Default 改成 RegistryView::Registry32 或 RegistryView::Registry64。

$old = 'HKLM:\SOFTWARE\MySoftware\Path=//Server/UNC/path/goes/here'
$new = 'HKLM:\SOFTWARE\MySoftware\Path=//Server/New/UNC/path/here'

function Copy-RegKeyRecursive {
    param(
        [Parameter(Mandatory)] [Microsoft.Win32.RegistryKey] $Source,
        [Parameter(Mandatory)] [Microsoft.Win32.RegistryKey] $Target
    )

    foreach ($valueName in $Source.GetValueNames()) {
        $kind = $Source.GetValueKind($valueName)
        $value = $Source.GetValue(
            $valueName,
            $null,
            [Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames
        )
        $Target.SetValue($valueName, $value, $kind)
    }

    foreach ($subKeyName in $Source.GetSubKeyNames()) {
        $srcSub = $Source.OpenSubKey($subKeyName, $false)
        $dstSub = $Target.CreateSubKey($subKeyName)
        try {
            Copy-RegKeyRecursive -Source $srcSub -Target $dstSub
        }
        finally {
            $srcSub.Close()
            $dstSub.Close()
        }
    }
}

$oldParentPath = $old.Substring(0, $old.LastIndexOf('\'))
$oldLeaf = $old.Substring($old.LastIndexOf('\') + 1)
$newParentPath = $new.Substring(0, $new.LastIndexOf('\'))
$newLeaf = $new.Substring($new.LastIndexOf('\') + 1)

$oldParentRel = $oldParentPath -replace '^HKLM:\\', ''
$newParentRel = $newParentPath -replace '^HKLM:\\', ''

$base = [Microsoft.Win32.RegistryKey]::OpenBaseKey(
    [Microsoft.Win32.RegistryHive]::LocalMachine,
    [Microsoft.Win32.RegistryView]::Default
)
try {
    $oldParent = $base.OpenSubKey($oldParentRel, $true)
    $newParent = $base.OpenSubKey($newParentRel, $true)

    if ($null -eq $oldParent) { throw "找不到旧父键:$oldParentPath" }
    if ($null -eq $newParent) { throw "找不到新父键:$newParentPath" }

    $oldKey = $oldParent.OpenSubKey($oldLeaf, $false)
    if ($null -eq $oldKey) { throw "找不到旧键:$old" }

    $newKey = $newParent.CreateSubKey($newLeaf)
    try {
        Copy-RegKeyRecursive -Source $oldKey -Target $newKey
    }
    finally {
        $oldKey.Close()
        $newKey.Close()
    }

    $oldParent.DeleteSubKeyTree($oldLeaf)
}
finally {
    if ($null -ne $oldParent) { $oldParent.Close() }
    if ($null -ne $newParent) { $newParent.Close() }
    $base.Close()
}

注意事项

  • 先确认目标键不存在,否则 Move-Item 或 CreateSubKey 可能报错,或者得到意外的结果。
  • 在同一个父键下改名时,Move-Item 最接近真正的重命名,通常能保留键的安全描述符。用 .NET 新建键再复制值时,显式 ACL 不一定自动保留;如果安全描述符很重要,需要额外处理。
  • 对 HKLM 操作通常需要管理员权限。
  • 脚本如果要在 32 位和 64 位 PowerShell 下运行,注册表视图可能不一样,按实际环境选择 RegistryView。
  • Rename-Item -NewName 失败,是 PowerShell 5.1 注册表 Provider 对这个参数的处理方式导致的;注册表本身允许 /。用反引号转义 / 解决不了。

备注:内容仅供参考。