Today I did some thinking about having some fun with UAC and PowerShell.
With Powershell v2 you can use the following code to execute “Get-Process” under elevated permissions:
Start-Process “$psHome\powershell.exe” -Verb Runas -ArgumentList ‘-command “Get-Process”‘
The “Get-Process” is just an example… you can put any code in there which you want to run with elevated permissions.
But then there is the executable. When you start one, for example when you call one from within a non-elevated PowerShell script, you will probably get hit by an UAC message. This can be a bit annoying, so here is a function you can use to start an executable from PowerShell with elevated permissions so you won’t get hit by UAC:
function Elevate-Process {
param ([string]$exe = $(Throw “Pleave provide the name and path of an executable”),[string]$arguments)
$startinfo = new-object System.Diagnostics.ProcessStartInfo
$startinfo.FileName = $exe
$startinfo.Arguments = $arguments
$startinfo.verb = “RunAs”
$process = [System.Diagnostics.Process]::Start($startinfo)
}
After some playing around with this, I did a little search on the internet about a self-elevating PowerShell script. A was amazed that I actually found one… and was flabbergasted when I saw the script came from Ben Armstrong (Microsoft)!
The script can be found here but since it’s a lot of code I’ve made it just a little bit smaller:
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
if ($myWindowsPrincipal.IsInRole($adminRole))
{
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + “(Elevated)”
clear-host
}
else {
$newProcess = new-object System.Diagnostics.ProcessStartInfo “PowerShell”;
$newProcess.Arguments = $myInvocation.MyCommand.Definition;
$newProcess.Verb = “runas”;
[System.Diagnostics.Process]::Start($newProcess);
exit
}
# Add the code of your script here
Beautiful; thanks!
I tried this but still get hit by UAC, it doesn’t matter where I run this either in CMD or Powershell, will always have an UAC prompt as an interactive window, which I am trying to avoid to automate the process. Thanks…any comments?
Hi Jonathan,
You’ll need to logoff/logon before the settings take effect.
Jeff.