Last active
February 18, 2021 15:07
-
-
Save JohnL4/0595e726b94f9ea1732fd9bebeec1479 to your computer and use it in GitHub Desktop.
Snippet of PowerShell to self-elevate a script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# --------------------------------------- Self-elevate the script if required. --------------------------------------- | |
# | |
# Physically include this in the client script, dot-sourcing will not work. | |
# From https://blog.expta.com/2017/03/how-to-self-elevate-powershell-script.html, but I made a few modifications myself. | |
# TODO: try making this a function. | |
try { | |
if (-Not ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) { | |
if ([int](Get-CimInstance -Class Win32_OperatingSystem | Select-Object -ExpandProperty BuildNumber) -ge 6000) { | |
Write-Verbose ("cmd type: {0}" -f $MyInvocation.MyCommand.CommandType) | |
$hasErrors = $false | |
# $CommandFile is the entire command line, passed as the -File argument to Powershell.exe. | |
$CommandFile = "`"" + $MyInvocation.MyCommand.Path + "`" " | |
foreach ($key in $MyInvocation.BoundParameters.Keys) { | |
$parm = $MyInvocation.BoundParameters[$key] | |
$parmType = $parm.GetType().Name | |
Write-Verbose ("parm {0} type is {1}" -f $key,$parmType) | |
if ($parmType -eq "SwitchParameter" <# -or $parmType -eq "Boolean" #> ) { | |
if ($parm) { | |
$CommandFile += ("-{0} " -f $key) | |
} | |
else { | |
# Sorry, I tried. | |
Write-Error ("Can't pass switch parameter -{0} with value `$False. Re-run as Administrator or don't specify `$False for a switch parameter." -f $key) ` | |
-Category InvalidArgument | |
$hasErrors = $true | |
} | |
} | |
else { | |
$CommandFile += ("-{0} {1} " -f $key,$parm) | |
} | |
} | |
$CommandFile += $MyInvocation.UnboundArguments | |
if ($hasErrors) { | |
throw "Errors were encountered" | |
} | |
if ($MyInvocation.MyCommand.Path -match '^S:\\') { | |
Write-Warning "This ain't gonna work if you don't have drive S: mapped as admin. Try 'net use s: \\p8files\Pulse8Share'." | |
} | |
Write-Verbose "Starting: $CommandFile" | |
# 'help powershell.exe -full' for Powershell args. -NoExit to debug. -NoProfile for faster startup and... better security?? | |
Start-Process -FilePath $PsHome\PowerShell.exe -Verb Runas ` | |
-ArgumentList @( <# "-NoExit", #> "-NoProfile", "-File", $CommandFile) | |
Exit | |
} | |
} | |
} | |
catch { | |
throw $Error[0] | |
} | |
# ------------------------------------------------- End self-elevate ------------------------------------------------- |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment