Skip to content

Instantly share code, notes, and snippets.

@mcc85s
Last active November 10, 2022 14:09
Show Gist options
  • Save mcc85s/785e7c83d14bd57cb7a52a2eefc94f73 to your computer and use it in GitHub Desktop.
Save mcc85s/785e7c83d14bd57cb7a52a2eefc94f73 to your computer and use it in GitHub Desktop.
self elevating powershell script
$ID = [Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()
If (!($ID.IsInRole("Administrator") -or $ID.IsInRole("Administrators")))
{
If (Get-CimInstance Win32_OperatingSystem | ? { [UInt32]$_.BuildNumber -ge 6000 })
{
Write-Host "Not running as admin, attempting elevation..."
$Command = $MyInvocation | % { "-File `"{0} {1}`"; Exit" -f $_.MyCommand.Path, $_.UnboundArguments }
Start-Process PowerShell -Verb Runas -Args $Command
}
Else
{
Throw "Must run as an administrator."
}
}
@mcc85s
Copy link
Author

mcc85s commented Sep 22, 2019

http://www.expta.com/2017/03/how-to-self-elevate-powershell-script.html <- Sort of the inspiration

I normally declare the namespace in my script, but, this works too. This snippet injects that string into the two places where that token needs to go, before the string becomes invoked into an expression in order to get a true or false answer.

The answer whether it's true or false will go on to the next correct process. if it's false, then it'll ask gcim if its 6000 or whatevs... if that's true then it will then execute the true statement. the true statement works with MyInvocation object opened up, and instead of having to type it twice.

SAPS is the default alias for start process. powershell doesn't need '.exe'. Argumentlist can be shortened to Args.
GCIM is short for Get-CimInstance...

Though it probably seems as if "Hey, how complicated could this snippet be?"

Well it took me months of rounding it down. Now, you have an option that works better than saying "[ Security.Principal.WindowsPrincipal ]" basically 3 times... it's ANNOYING.

I understand. Microsoft made it a pain in the neck on purpose. Whatevs...

@vivek1986
Copy link

vivek1986 commented Jul 26, 2022

What's so special or necessary about GCIM 6000, I tried and this works pretty good too(Windows 10/11) and it doesn't forget current directory:

$Loc = Get-Location
"Security.Principal.Windows" | % { IEX "( [ $_`Principal ] [$_`Identity ]::GetCurrent() ).IsInRole( 'Administrator' )" } | ? {
    $True | % { $Arguments =  @('-NoProfile','-ExecutionPolicy Bypass','-NoExit','-File',"`"$($MyInvocation.MyCommand.Path)`"","\`"$Loc\`"");
    Start-Process -FilePath PowerShell.exe -Verb RunAs -ArgumentList $Arguments; } }

(Get-Location).ToString()
## Any PS code that needs elevation
Read-Host

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment