Last active
August 29, 2015 14:03
-
-
Save AdilHindistan/244a79dd4a071d261055 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ##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