运行 PowerShell,管理员模式,在 shell 上下文菜单的目录中

Run PowerShell, admin mode, in directory from shell context menu

我使用下面显示的代码创建了一个资源管理器 Shell 级联上下文菜单,用于在目录中打开 PowerShell。 (注意:我在管理命令中硬编码了一个示例路径用于测试。)

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Directory\shell\powershell.exe]
"MUIVerb"=""
"SubCommands"="powershell;powershell_admin"
"Icon"="PowerShell.exe"

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\powershell]
@="Open PowerShell here"

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\powershell\command]
@="powershell.exe -NoLogo -NoExit -Command Set-Location '%V'"

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\powershell_admin]
@="Open PowerShell (admin) here"

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\CommandStore\shell\powershell_admin\command]
@="powershell.exe -Command 'Start-Process PowerShell -ArgumentList \"-NoLogo -NoExit -Command Set-Location C:\Python27\" -Verb RunAs'"

非管理员命令完美运行。 admin 命令忽略 ArgumentList 中的所有内容。

如果我打开 PowerShell 并直接执行单引号 (') 中的代码,它就可以正常工作。例如:

Start-Process PowerShell -ArgumentList \"-NoLogo -NoExit -Command Set-Location C:\Python27\" -Verb RunAs

但是当从上下文菜单执行时,它以管理员模式打开但显示徽标并且不执行 Set-Location。

提前致谢

这是一个很棒的实用程序。 我安装了注册表条目来进行实验,现在它可以正常工作了,我可能会保留它。

在我的实验中,window 立即关闭,甚至在它打开 UAC 对话框之前,直到我将外部命令用转义双引号括起来,将内部参数用单引号括起来。然后它对除 Program Files 下的文件夹之外的每个文件夹都能正常工作。为此,我们需要将 %v 括在单引号中,并将其周围的双引号双引号转义:

@="powershell.exe -command \"start-process powershell.exe -ArgumentList \\"-NoLogo -NoExit -Command Set-Location '%v'\\"  -verb RunAs\""

我使用了 %v - 上下文文件夹名称,这似乎是您基于菜单标签的初衷 'Open Powershell (admin) here'。

调试说明:

  • 为了实验,在 Regedit.exe 中进行更改并让导出功能根据需要添加转义字符会更容易一些
  • 在 Windows 10 中,您可以直接在 Regedit.exe 中进行更改,上下文 menu/action 会立即更新,我通过在菜单标签 [=23= 中添加时间戳来确认这一点]
  • 在其他版本的 Windows 中,可能需要停止并重新启动 explorer.exe