04 Nov 2011 @ 8:24 PM 

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

Post to Twitter

Posted By: Jeff Wouters
Last Edit: 23 Apr 2012 @ 06:58 AM

EmailPermalink
Tags
Categories: PowerShell, Windows



Get Adobe Flash player
 Last 50 Posts
 Back
Change Theme...
  • Users » 1
  • Posts/Pages » 164
  • Comments » 150
Change Theme...
  • VoidVoid « Default
  • LifeLife
  • EarthEarth
  • WindWind
  • WaterWater
  • FireFire
  • LightLight

About



    No Child Pages.

Contact



    No Child Pages.