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."
}
}
@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