Skip to content

Instantly share code, notes, and snippets.

@colebrumley
Last active October 24, 2017 18:28
Show Gist options
  • Save colebrumley/2e1995262c64c94ceba92236c745685a to your computer and use it in GitHub Desktop.
Save colebrumley/2e1995262c64c94ceba92236c745685a to your computer and use it in GitHub Desktop.
Reinvoke the current PowerShell script as Admin
function Launch-Admin-Shell () {
# Get the ID and security principal of the current user account
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
# Get the security principal for the Administrator role
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
# Check to see if we are currently running "as Administrator"
if ($myWindowsPrincipal.IsInRole($adminRole))
{
# We are running "as Administrator" - so change the title and background color to indicate this
$Host.UI.RawUI.WindowTitle = $myInvocation.MyCommand.Definition + "(Elevated)"
$Host.UI.RawUI.BackgroundColor = "DarkBlue"
clear-host
}
else
{
# Create a new process object that starts PowerShell
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";
# Specify the current script path and name as a parameter
$newProcess.Arguments = $myInvocation.MyCommand.Definition;
# Indicate that the process should be elevated
$newProcess.Verb = "runas";
# Loads the UserProfile into the subprocess
$newProcess.LoadUserProfile = $true;
# Start the new process
[System.Diagnostics.Process]::Start($newProcess);
# Exit from the current, unelevated, process
exit
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment