Gaining administrator privileges in PowerShell

Solution 1:

The Powershell v2 way, according to Microsoft, is to right click on the shortcut and choose Run as Administrator.

And to elevate within a Powershell window:

start-process powershell –verb runAs

Which from a cmd.exe batch file, shortcut or Run line would look something (repetitively) like this:

powershell "start-process powershell -verb runas"

Solution 2:

The easiest way to do this is to launch Powershell with administration tokens. To do this, you right click on Powershell (or a shortcut to it) and click on "run as administrator". Alternatively you can use elevate.cmd.


Solution 3:

This opens a new powershell instance:

function Run-Elevated ($scriptblock)
{
  # TODO: make -NoExit a parameter
  # TODO: just open PS (no -Command parameter) if $scriptblock -eq ''
  $sh = new-object -com 'Shell.Application'
  $sh.ShellExecute('powershell', "-NoExit -Command $scriptblock", '', 'runas')
}

I expect that there are issues with this - in particular, you won't get the output of your scriptblock back in the calling script. On the other hand, it will be there in the new PS instance so you can hack with it there.


Solution 4:

If you want to always run PowerShell with admin priveleges, you can right-click the PowerShell shortcut, then click the "Advanced..." button on the "Shortcut" tab, then select "Run as Administrator".