PowerShell注册表子路径访问错误:路径拼接异常排查与解决
问题:PowerShell遍历注册表子项时路径拼接错误导致Set-ItemProperty失败
我编写PowerShell脚本用于修改指定注册表路径HKLM:\SOFTWARE\WOW6432Node\Sims下所有子项的Locale值。硬编码变量修改单个子项时一切正常,但遍历所有子项时,得到的子项路径是当前工作目录与注册表子项路径的拼接,导致Set-ItemProperty报错找不到路径。例如选择泰语执行时,报错路径为当前工作目录拼接注册表子项路径,提示该路径不存在。
原因分析
Get-ChildItem在注册表路径下返回的是RegistryKey对象,当你直接把这个对象传给Set-ItemProperty的-Path参数时,PowerShell会自动调用对象的ToString()方法获取路径字符串。但RegistryKey的ToString()仅返回子项的名称(比如The Sims 3),而非完整的注册表路径。此时如果当前工作目录是文件系统路径(比如C:\Users\mylue\Documents\Bordel\TS3),PowerShell会默认将这个子项名称拼接到当前文件系统路径后,形成无效的混合路径,最终导致找不到路径的错误。
解决方法
有两种可靠的方式获取子项的完整注册表路径:
- 使用RegistryKey对象的
.PSPath属性:该属性存储了包含注册表提供程序前缀的完整路径(比如Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Sims\The Sims 3),可以直接传给-Path参数。 - 拼接完整路径:用
Join-Path将父路径simsPath与子项的.Name属性拼接成完整的注册表路径。
修改后的代码
以下是采用第一种方法(使用.PSPath)修改后的完整脚本:
$simsPath = "HKLM:\SOFTWARE\WOW6432Node\Sims" $Languages = @{ "Chinese (Simple)" = "zh-CN" "Chinese (traditional)" = "zh-TW" # 省略其他语言项 "Swedish" = "sv-SE" "Thai" = "th-TH" } $correctInput = $false $Languages.Keys | ForEach-Object { Write-Host $_ } do { $Language = Read-Host -Prompt "`nType the language you want for your game" $Language = $Language.ToLower() $targetLocale = $Languages[$Language] $ts3Path = Join-Path $simsPath "The Sims 3" if ((Get-ItemProperty -Path $ts3Path).Locale -eq $targetLocale) { Write-Host "Your game is already in $($Language.ToUpper()) ! " } elseif ($targetLocale) { $correctInput = $true Write-Host "You chose '$($Language.ToUpper())'" try { $simsFolders = Get-ChildItem -LiteralPath $simsPath | Where-Object { $_.PSIsContainer } foreach ($folder in $simsFolders) { # 使用.PSPath获取完整注册表路径 Set-ItemProperty -Path $folder.PSPath -Name "Locale" -Value $targetLocale if ((Get-ItemProperty -Path $folder.PSPath).Locale -eq $targetLocale) { Write-Host "Changed the language for $($folder.Name)" } else{ Write-Host "Something went wrong, couldn't change the language for $($folder.Name)." break } } } catch { Write-Host "An unexpected error occurred: $_" } } else { Write-Host "Couldn't recognize the language, try again." -ForegroundColor yellow } } while (-not $correctInput)
关键修改点
- 将
Set-ItemProperty -Path $folder改为Set-ItemProperty -Path $folder.PSPath,确保传入的是完整的注册表路径。 - 同步修改后续
Get-ItemProperty的路径参数,保持一致性。 - 优化变量命名(如
$targetLocale),提升代码可读性。
内容的提问来源于stack exchange,提问作者Mylue
相关产品推荐
相关产品推荐

