Skip to content

Instantly share code, notes, and snippets.

@mmotti
Last active May 14, 2024 21:58
Show Gist options
  • Save mmotti/3661ca49807c93f139d459a237547daf to your computer and use it in GitHub Desktop.
Save mmotti/3661ca49807c93f139d459a237547daf to your computer and use it in GitHub Desktop.
Function Test-IsAdminElevated {
if (([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::
GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
return $true
}
else {
return $false
}
}
# Re-launch with admin elevation and -NoExit
# Match "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -ExecutionPolicy Bypass -NoExit -File
# Bit safer in case there are some file names that incorrectly flag a match
$stripRegex = '^[^\s]+(\s-[^\s]+(?:\s[^\s]+)?)+'
$noExitSwitchPresent = $false
if ([System.Environment]::CommandLine -match $stripRegex) {
if ($Matches[0] -match '-NoExit') {
$noExitSwitchPresent = $true
}
}
if (!(Test-IsAdminElevated) -or !($noExitSwitchPresent)) {
$newPSProcess = New-Object System.Diagnostics.ProcessStartInfo 'PowerShell'
$newPSArguments = '-ExecutionPolicy Bypass'
if (!($noExitSwitchPresent)) {
$newPSArguments += ' -NoExit'
}
if (!(Test-IsAdminElevated)) {
$newPSProcess.Verb = 'RunAs'
}
$newPSArguments += " -File `"$($Script:MyInvocation.MyCommand.Path)`""
$newPSProcess.Arguments = $newPSArguments
$newPSProcess.WorkingDirectory = Split-Path($Script:MyInvocation.MyCommand.Path) -Parent
[System.Diagnostics.Process]::Start($newPSProcess)
exit
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment