Skip to content

Instantly share code, notes, and snippets.

@m5knt
Last active August 20, 2023 22:17
Show Gist options
  • Save m5knt/4956d423d0b361d417bd319c7605e998 to your computer and use it in GitHub Desktop.
Save m5knt/4956d423d0b361d417bd319c7605e998 to your computer and use it in GitHub Desktop.
uac & powershell launcher
@(echo "`" >nul & goto :__BATCH__) & rem ") | Out-Null
<#
:: UAC Elevation & Powershell Launcher
:: MIT License (c) Yukio KANEDA
:__BATCH__
@if "%~1" neq "/?" call :__MAIN__ %0 %* <nul & exit /b
@shift /1 & call :__MAIN__ %0 /h <nul & exit /b
:__USAGE__
if not exist %_000%.ps1 (
echo.Usage: %0 [uac^|pow^|pwsh^|...] [Options...]
exit /b
)
for /f "usebackq delims=" %%i in (`more +1 "%_000%.ps1"`) do (
if "%%i" == "----" exit /b
echo.%%i
)
:__MAIN__
@echo off
setlocal
shift
set _000=%~dpn0
set _CMD=powershell
set "_ARG=-ExecutionPolicy Bypass"
if exist %_000%.ps1 set "_ARG=-ExecutionPolicy Bypass -Command %_000%.ps1"
if "%~1" == "posh" ( set "_ARG=-ExecutionPolicy Bypass" & shift )
if "%~1" == "pwsh" ( set "_ARG=-ExecutionPolicy Bypass" & set "_CMD=pwsh" & shift )
if "%~1" == "uac" ( set "_UAC=#UAC#" & set "_ARG=" & shift )
:__GETARG__
if "%~1" == "--help" goto :__USAGE__
if "%~1" == "-help" goto :__USAGE__
if "%~1" == "/help" goto :__USAGE__
if "%~1" == "-h" goto :__USAGE__
if "%~1" == "-?" goto :__USAGE__
if "%~1" == "/h" goto :__USAGE__
if "%~1" == "/?" goto :__USAGE__
set _VAL=%1
if not defined _VAL goto :__FINI_GETARG__
set _ARG=%_ARG% %_VAL%
shift
goto :__GETARG__
:__FINI_GETARG__
rem set _ARG=%_ARG:"="""%
where /q %_CMD%
if ERRORLEVEL 1 (
echo.'%_CMD%' not found.
exit /b 1
)
if defined _UAC goto :__UAC__
%_CMD% %_ARG% <con
exit /b
:__UAC__
(type "%_000%.bat" & echo.) | %_CMD% -ExecutionPolicy ByPass -NoProfile -Command -
exit /b
#>
try {
$arg = if ($Env:_ARG) {"/c cd /d ""$PWD"" & cmd /c$Env:_ARG"} else {"/k cd /d ""$PWD"""}
Write-Host $arg
$p = Start-Process -PassThru -Verb RunAs -Wait $Env:ComSpec -ArgumentList $arg
exit $p.exit
}
catch { exit 127 } exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment