Tuesday, September 24, 2013

Auto-elevating PowerShell scripts

A little while back I wrote a blog about auto-elevating batch-files. Recently I found that Keith Hill has written something similar for PowerShell, which is nowadays the thing to use.....

Anyways, here's a repeat of Keith Hill's work, with all credits to Keith of cource.

See http://rkeithhill.wordpress.com/2013/04/05/powershell-script-that-relaunches-as-admin/ for more information regarding the code below.

function IsAdministrator
{
$Identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$Principal = New-Object System.Security.Principal.WindowsPrincipal($Identity)
$Principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
}

function IsUacEnabled
{
(Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System).EnableLua -ne 0
}

#
# Main script
#
if (!(IsAdministrator))
{
if (IsUacEnabled)
{
[string[]]$argList = @('-NoProfile', '-NoExit', '-File', $MyInvocation.MyCommand.Path)
$argList += $MyInvocation.BoundParameters.GetEnumerator() | Foreach {"-$($_.Key)", "$($_.Value)"}
$argList += $MyInvocation.UnboundArguments
Start-Process PowerShell.exe -Verb Runas -WorkingDirectory $pwd -ArgumentList $argList
return
}
else
{
throw "You must be administrator to run this script"
}
}