Skip to content

Instantly share code, notes, and snippets.

@AdilHindistan
Last active August 29, 2015 14:03
Show Gist options
  • Select an option

  • Save AdilHindistan/244a79dd4a071d261055 to your computer and use it in GitHub Desktop.

Select an option

Save AdilHindistan/244a79dd4a071d261055 to your computer and use it in GitHub Desktop.
##AH - Adil Hindistan - Self Elevating Script
# http://rkeithhill.wordpress.com/2013/04/05/powershell-script-that-relaunches-as-admin/
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"
}
}
## One liner to check for admin & quit if not
if (-not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { write-error "You must run this script from an Administrator PowerShell instance"; return }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment