Skip to content

Instantly share code, notes, and snippets.

@sdovnic
Forked from zblesk/self-elevating-script.ps1
Last active February 6, 2023 18:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sdovnic/e0121316734049e59ef3 to your computer and use it in GitHub Desktop.
Save sdovnic/e0121316734049e59ef3 to your computer and use it in GitHub Desktop.
A self-elevating powershell script.
if (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
"Running as admin in $PSScriptRoot"
}
else
{
"NOT running as an admin!"
Start-Process powershell -WorkingDirectory $PSScriptRoot -Verb runAs -ArgumentList "-noprofile -noexit -file $PSCommandPath"
return "Script re-started with admin privileges in another shell. This one will now exit."
}
"Doing this only as admin."
@vivek1986
Copy link

Smaller but not so cleaner:

$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