Skip to content

Instantly share code, notes, and snippets.

@dancing-groot
Last active May 17, 2023 16:59
Show Gist options
  • Save dancing-groot/a6eb5b4313f1a8e695a48e11d6e152ec to your computer and use it in GitHub Desktop.
Save dancing-groot/a6eb5b4313f1a8e695a48e11d6e152ec to your computer and use it in GitHub Desktop.
Add this if your script (or a portion of) needs to run with administrative privileges
function Invoke-ElevatedRights
{
[CmdletBinding()]
param()
<#
.SYNOPSIS
Relaunch the script with elevated rights if required
.DESCRIPTION
Checks if the current user is running the script 'As Administrator'
If they are not, relaunch the script in a new process with elevated rights
Bonus feature: Any parameters passed to the original script will be reused for the elevated one
.LINK
https://gist.github.com/dancing-groot/a6eb5b4313f1a8e695a48e11d6e152ec
.NOTES
Version: 2023.05.17
Author: @dancing-groot
#>
# Required for using the invocation of the script, not the function
$invocation = (Get-Variable MyInvocation -Scope 1).Value
# 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)))
{
# Not running "as Administrator"
# Create a new process object that starts PowerShell
$newProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell"
# Get the list of parameters used in this script to pass them along (if any)
$scriptArguments = ""
if (($invocation.BoundParameters.keys).Count -ne 0)
{
foreach ($key in $invocation.BoundParameters.keys)
{
$value = (get-variable $key).Value
$scriptArguments += " -$key $value"
}
}
# Specify the current script path and name as a parameter
$newProcess.Arguments = "-File $($invocation.MyCommand.Source) $scriptArguments"
# Indicate that the process should be elevated
$newProcess.Verb = "RunAs"
# Start the new process
[System.Diagnostics.Process]::Start($newProcess)
# Exit from the current unelevated, process
exit
}
} # Invoke-ElevatedRights
Invoke-ElevatedRights
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment