使用PowerShell将快捷方式固定到开始菜单时遭遇权限错误
使用PowerShell将快捷方式固定到开始菜单时遭遇权限错误
我来帮你解决这个权限问题!首先我注意到你用Open这类动词能正常工作,但Pin to Start就触发权限错误,而且你是在管理员PowerShell里执行的——这大概率就是问题的核心。
先再明确下你的代码(方便后续分析):
$desktopPath = [System.Environment]::GetFolderPath('Desktop') $shortcutName = "XAMPP Control Panel.lnk" # Name of the shortcut $shortcutPath = Join-Path $desktopPath $shortcutName $Shell = New-Object -ComObject Shell.Application $Folder = $Shell.Namespace((Get-Item $shortcutPath).DirectoryName) $Item = $Folder.ParseName((Get-Item $shortcutPath).Name) $Item.Verbs() | ForEach-Object { Write-Output $_.Name } $Verb = $Item.Verbs() | Where-Object {$_.Name -eq "&Pin to Start"} if ($Verb) { $Verb.DoIt() Write-Output "Pinned." } else { Write-Output "The item is already pinned or cannot be pinned." }
问题根源
将快捷方式固定到开始菜单是用户级别的操作,相关配置文件存储在当前登录用户的%APPDATA%\Microsoft\Windows\Start Menu目录下。当你用管理员PowerShell运行时,Shell.Application COM对象是在管理员的安全上下文下执行的,这个上下文无法直接访问普通用户的专属AppData目录,也就导致了权限错误——而Open这类动词只需要读取快捷方式本身,不需要写入用户专属目录,所以能正常工作。
解决方案
方案1:用普通用户PowerShell执行(最简单)
直接关闭管理员PowerShell,打开普通的用户PowerShell窗口(不需要右键选择“以管理员身份运行”),然后重新运行你的代码。这样脚本就在当前登录用户的上下文下执行,能正常访问开始菜单的存储位置,权限问题会直接消失。
方案2:必须用管理员权限时,切换到当前用户上下文执行
如果你的脚本必须在管理员环境下运行其他操作,只需要把固定开始菜单的部分切换到普通用户上下文执行。可以用Start-Process启动一个非管理员的PowerShell进程来执行固定逻辑:
# 把固定开始菜单的代码封装成脚本内容 $pinScript = @" `$desktopPath = [System.Environment]::GetFolderPath('Desktop') `$shortcutName = "XAMPP Control Panel.lnk" `$shortcutPath = Join-Path `$desktopPath `$shortcutName `$Shell = New-Object -ComObject Shell.Application `$Folder = `$Shell.Namespace((Get-Item `$shortcutPath).DirectoryName) `$Item = `$Folder.ParseName((Get-Item `$shortcutPath).Name) `$Verb = `$Item.Verbs() | Where-Object {`$_.Name -eq "&Pin to Start"} if (`$Verb) { `$Verb.DoIt() Write-Output "Pinned successfully." } else { Write-Output "The item is already pinned or cannot be pinned." } "@ # 启动非管理员PowerShell执行这段脚本 Start-Process powershell.exe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -Command `"$pinScript`""
方案3:检查快捷方式本身的权限
如果上面两个方案都不行,可以检查桌面快捷方式的权限:
- 右键点击
XAMPP Control Panel.lnk,选择“属性” - 切换到“安全”选项卡,确保当前登录用户(包括管理员组)有读取和修改的权限
- 如果权限不足,点击“编辑”添加对应的权限后再重试脚本
额外提示
你可以先运行$Item.Verbs()看看输出里有没有&Pin to Start,如果没有,可能是该快捷方式已经被固定,或者系统不支持固定它(比如某些系统内置程序的限制)。
备注:内容来源于stack exchange,提问作者Arash Seifi
相关产品推荐
相关产品推荐

