#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

Filed in: Columns, Tips and Tricks Tags: , ,

6 Responses to "#PSTip How to start an elevated PowerShell from Windows Explorer"

  1. Stephan Onisick says:

    Awesome!! I’m used to you can’t get here from there.

  2. Kevin Michael Rivera says:

    That is a great tip! Thank you.

    Is there a way to do it with another account?

  3. John L says:

    The only difference between running as Admin and running as normal user seems to be the key (runas vs something else). Now I’m confused, what if I want multiple commands running as admin in the context menu?

  4. Stephen Bridgett says:

    hmm, Powershell starts but will not surface. I can see that it is open (on the taskbar) but even clicking on the taskbar view of the open window will not cause it to show

Leave a Reply

Submit Comment

© 2018 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: