#PSTip How to start an elevated PowerShell from Windows Explorer

Note: This tip requires PowerShell 2.0 or above.

The next time you are working in a folder and need to open a Windows PowerShell console directly to that location, it would be nice to have ‘Open Windows PowerShell Here as Administrator’ option on a context menu. To accomplish that, you’ll need to create a few Registry keys, and an elevated Windows PowerShell console will be just a right-click away from a folder icon, a drive icon, or inside of an open folder. To run this code, start Windows PowerShell with the “Run as administrator” option.

$menu = 'Open Windows PowerShell Here as Administrator'
$command = "$PSHOME\powershell.exe -NoExit -NoProfile -Command ""Set-Location '%V'"""

'directory', 'directory\background', 'drive' | ForEach-Object {
    New-Item -Path "Registry::HKEY_CLASSES_ROOT\$_\shell" -Name runas\command -Force |
    Set-ItemProperty -Name '(default)' -Value $command -PassThru |
    Set-ItemProperty -Path {$_.PSParentPath} -Name '(default)' -Value $menu -PassThru |
    Set-ItemProperty -Name HasLUAShield -Value ''
}

This is how the modified HKEY_CLASSES_ROOT\Directory\shell and HKEY_CLASSES_ROOT\Directory\Background\shell Registry keys look like (click for larger image):
OpenPowerShellHereAsAdmin

These Registry changes will create new entry on the context menu and this is how it looks when you right-click a folder icon, or inside of the open folder:
ContextMenu
Context menu when you right-click a folder icon

ContextMenuBackground
Context menu when you right-click inside (on the background) of an open folder

About the author: Aleksandar Nikolic

Aleksandar is a PowerShell MVP and a co-founder of PowerShell Magazine. He is a frequent speaker at the conferences and participates regularly in IT Pro user groups worldwide. Recently, Aleksandar co-authored the highly respected Administrator’s Guide to Windows PowerShell Remoting. Follow him on Twitter at @alexandair

Related Posts

%d bloggers like this: