使用PowerShell脚本固定PowerShell图标到任务栏时报空值错误如何修复
PowerShell固定任务栏脚本报错修复方案
报错根因
所有空值调用报错均为链式触发,核心问题为两点:
- 脚本未以管理员权限运行,无注册表写入权限,执行
$Key2 = (Get-Item $KeyPath1).OpenSubKey($KeyPath2, $true)时无权限打开可写的注册表子项,返回空值,后续所有基于$Key2衍生的$Key3、$Key4变量全部为空,调用方法时触发报错 - 原有代码无空值校验逻辑,未对注册表操作结果做合法性判断就直接调用方法
修复后完整代码
# 校验管理员权限 $currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent()) if (-not $currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) { Write-Error "请以管理员身份运行PowerShell后再执行此脚本" exit 1 } $Target="C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" if (!(Test-Path $Target)) { Write-Warning "$Target 不存在" exit 1 } $KeyPath1 = "HKCU:\SOFTWARE\Classes" $KeyPath2 = "*" $KeyPath3 = "shell" $KeyPath4 = "{:}" $ValueName = "ExplorerCommandHandler" # 校验固定任务栏的系统接口存在 $commandStorePath = "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\Windows.taskbarpin" if (-not (Test-Path $commandStorePath)) { Write-Error "系统未找到固定任务栏的对应接口,建议手动右键powershell.exe选择固定到任务栏" exit 1 } $ValueData = (Get-ItemProperty $commandStorePath).ExplorerCommandHandler $Key1 = Get-Item $KeyPath1 $Key2 = $Key1.OpenSubKey($KeyPath2, $true) # 校验注册表项打开成功 if ($null -eq $Key2) { Write-Error "无法打开对应注册表项,请检查权限" exit 1 } $Key3 = $Key2.CreateSubKey($KeyPath3, $true) $Key4 = $Key3.CreateSubKey($KeyPath4, $true) $Key4.SetValue($ValueName, $ValueData) $Shell = New-Object -ComObject "Shell.Application" $Folder = $Shell.Namespace((Get-Item $Target).DirectoryName) $Item = $Folder.ParseName((Get-Item $Target).Name) $Item.InvokeVerb("{:}") # 清理临时注册表项 $Key3.DeleteSubKey($KeyPath4) if ($Key3.SubKeyCount -eq 0 -and $Key3.ValueCount -eq 0) { $Key2.DeleteSubKey($KeyPath3) } # 释放注册表句柄 $Key4.Close() $Key3.Close() $Key2.Close() $Key1.Close() Write-Host "PowerShell已成功固定到任务栏"
注意事项
- 必须以管理员身份启动PowerShell后再执行脚本,否则会触发权限报错
- 该脚本适配Win10全版本、Win11 21H2及更早版本,Win11 22H2之后的系统修改了任务栏固定逻辑,脚本失效时可直接手动找到
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe,右键选择「固定到任务栏」即可
内容的提问来源于stack exchange,提问作者jimmyafflick
相关产品推荐
相关产品推荐

