Gaining administrator privileges in PowerShell
I only have one account on my Windows Vista machine, and that user has administrative privileges. However, when I try to execute a command within PowerShell to kill a certain process, I'm greeted with an "Access is denied" message. How do I become the administrator?
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.
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"
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.
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".
You can use this to self-elevate a script when ran:
#at top of script
if (!
#current role
(New-Object Security.Principal.WindowsPrincipal(
[Security.Principal.WindowsIdentity]::GetCurrent()
#is admin?
)).IsInRole(
[Security.Principal.WindowsBuiltInRole]::Administrator
)
) {
#elevate script and exit current non-elevated runtime
Start-Process `
-FilePath 'powershell' `
-ArgumentList (
#flatten to single array
'-File', $MyInvocation.MyCommand.Source, $args `
| %{ $_ }
) `
-Verb RunAs
exit
}
#example program, this will be ran as admin
$args
Pause
NB this still adheres to security rules (like execution policy) and will nicely prompt for UAC. This can be worked around, but you shouldn't.