Skip to content

Instantly share code, notes, and snippets.

@boredwz
Last active May 16, 2025 21:17
Show Gist options
  • Select an option

  • Save boredwz/f7e908dd8d25cc8345ef2065e093d63c to your computer and use it in GitHub Desktop.

Select an option

Save boredwz/f7e908dd8d25cc8345ef2065e093d63c to your computer and use it in GitHub Desktop.
(PowerShell script) Self-elevate to Administrator, preserve arguments, use Windows Terminal console when possible.
<#
.SYNOPSIS
Self-elevate to Administrator and preserve arguments.
.DESCRIPTION
Self-elevate to Administrator, preserve arguments, use Windows Terminal console when possible.
.EXAMPLE
# Import
iwr -useb 'https://gist.githubusercontent.com/boredwz/f7e908dd8d25cc8345ef2065e093d63c/raw/admin.ps1' | iex
# Elevate if not admin
If (-not (Admin)) {Admin -Elevate $MyInvocation.Line;return}
# ADMINISTRATOR
.EXAMPLE
iwr -useb 'https://gist.githubusercontent.com/boredwz/f7e908dd8d25cc8345ef2065e093d63c/raw/admin.ps1' | iex
If (!(Admin)) {
Write-Warning 'Administrator rights required.';'Press [Enter] or [Y] to run as Admin...'
if([Console]::ReadKey($true).Key -match '^(Enter|Y)') {Admin -Elevate $MyInvocation.Line '"echo test1"|iex;"test2"'};return
}
#>
function Admin([switch]$Elevate, $MyInv, [string]$C) {
if (!$Elevate) {return ('([{0}Principal] [{0}Identity]::GetCurrent()).IsInRole([{0}BuiltInRole]::Administrator)' -f 'Security.Principal.Windows'|iex)}
$wt = if(gcm wt -ea 0){"\\"}else{""}
$cm = ('[Console]::Title'|%{'{0}="{1}";cd -l ''{2}'';{3};{4}' -f $_,(iex $_),$pwd,($MyInv -join ';'),$C}) -replace '"',"$wt\`""
"-nol -noe -ep bypass -c"|%{if($wt){$exe="wt";$ar="powershell",$_,($cm -replace ';','\;')}else{$exe="powershell";$ar=$_,$cm}}
start $exe $ar -wor "~" -v runAs
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment