Sunday, October 8, 2017

You can't elevate an existing PowerShell prompt, but you can relaunch PowerShell in the current directory

One user wanted to know how to elevate an existing PowerShell prompt to administrator. Unfortunately, this is not possible because the primary token of a process cannot be replaced after it starts running. It is, however, very simple to prompt for the elevation of a new PowerShell window, and the current directory can be sent over via a startup command.

Start-Process powershell -Verb runas -ArgumentList "-NoExit -c cd '$pwd'"

Note that the $pwd (an object which stringifies to the current directory path) is expanded in the original process. Usually, starting PowerShell with startup commands would cause it to exit after finishing those commands, but -NoExit leaves it around for interactive use.

No comments:

Post a Comment