You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell从逆序节点数组生成层级注册表路径数组

问题:将注册表路径片段数组转换为层级路径数组并自动创建缺失键

现有PowerShell代码:

$RegKey = "HKLM:\OFFLINE_NTUSER\SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost\1\2\3\4\5\6\7\8\9"

$CurrentParent = $RegKey
$PresentParentFound = $false
$ParentList = @()

While ($PresentParentFound -eq $false) {    
    if (Test-Path $CurrentParent) {   
        $PresentParentFound = $true       
    }
    else {
        $NextParent = Split-Path $CurrentParent -Parent
        $Last = Split-Path $CurrentParent -Leaf
        $ParentList +=$Last
        $CurrentParent = $NextParent
    }
}

执行后$ParentList数组内容为:

9
8
7
6
5
4
3
2
1

需求是将该数组转换为包含以下层级注册表路径的数组:

HKLM:\OFFLINE_NTUSER\SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost\1
HKLM:\OFFLINE_NTUSER\SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost\1\2
HKLM:\OFFLINE_NTUSER\SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost\1\2\3
HKLM:\OFFLINE_NTUSER\SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost\1\2\3\4
HKLM:\OFFLINE_NTUSER\SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost\1\2\3\4\5
HKLM:\OFFLINE_NTUSER\SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost\1\2\3\4\5\6
HKLM:\OFFLINE_NTUSER\SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost\1\2\3\4\5\6\7
HKLM:\OFFLINE_NTUSER\SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost\1\2\3\4\5\6\7\8
HKLM:\OFFLINE_NTUSER\SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost\1\2\3\4\5\6\7\8\9

最终目的是编写注册表键创建函数,调用指定完整路径时自动创建所有缺失父键。


解决方案

方法1:生成层级路径数组并逐个创建键

通过反转缺失节点数组、安全拼接路径的方式生成目标数组,再依次创建键:

$RegKey = "HKLM:\OFFLINE_NTUSER\SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost\1\2\3\4\5\6\7\8\9"

$CurrentParent = $RegKey
$PresentParentFound = $false
$ParentList = @()

# 定位已存在的最深父键,收集缺失节点(倒序)
While (-not $PresentParentFound) {    
    if (Test-Path $CurrentParent) {   
        $PresentParentFound = $true       
    }
    else {
        $Last = Split-Path $CurrentParent -Leaf
        $ParentList += $Last
        $CurrentParent = Split-Path $CurrentParent -Parent
    }
}

# 反转节点数组得到正序序列(1,2,...9)
$reversedNodes = $ParentList | Reverse

# 生成层级路径数组
$targetPaths = @()
$currentPath = $CurrentParent
foreach ($node in $reversedNodes) {
    $currentPath = Join-Path -Path $currentPath -ChildPath $node
    $targetPaths += $currentPath
}

# 创建所有缺失的注册表键
foreach ($path in $targetPaths) {
    if (-not (Test-Path $path)) {
        New-Item -Path $path -Force | Out-Null
    }
}

# 输出验证目标路径
$targetPaths

方法2:直接利用PowerShell内置功能创建完整路径

如果不需要生成层级路径数组,仅需自动创建所有缺失父键,可直接用New-Item的-Force参数一步到位:

$RegKey = "HKLM:\OFFLINE_NTUSER\SOFTWARE\Microsoft\Windows\CurrentVersion\AppHost\1\2\3\4\5\6\7\8\9"

# -Force参数会自动创建所有缺失的父键
New-Item -Path $RegKey -Force | Out-Null

内容的提问来源于stack exchange,提问作者Rafi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 20:07:17