#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):

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:

Context menu when you right-click a folder icon

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

Share on: