Skip to content

Instantly share code, notes, and snippets.

@IAmStoxe
Created April 12, 2021 23:17
Show Gist options
  • Save IAmStoxe/6e5bff94301076e502384435ebd8c79f to your computer and use it in GitHub Desktop.
Save IAmStoxe/6e5bff94301076e502384435ebd8c79f to your computer and use it in GitHub Desktop.
Check if the local admin needs to run the script as administrator. If not a local admin relaunch script as admin user.
#Check if PowerShell version is greater than 2. If not, set $PSSriptRoot.
if ($PSVersionTable.PSVersion.Major -lt 3) {
$PSScriptRoot = Split-Path -Parent $MyInvocation.MyCommand.Definition
}
#Check if the user is a local admin. If they are, set $LocalAdmin to $True.
$LocalAdmin = $false
if ((net localgroup administrators) -match ([System.Environment]::UserDomainName + "\\" + [System.Environment]::Username)) {
$LocalAdmin = $true
}
if ($LocalAdmin) {
#Check if the local admin needs to run the script as administrator
if (-not ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
$arguments = "& '" + $MyInvocation.MyCommand.Definition + "'"
Start-Process powershell -Verb runas -ArgumentList $arguments
break
}
}
else {
#Not a local admin. Relaunch script as admin user.
Start-Process -Credential $credential (Join-Path $PSHome powershell.exe) -ArgumentList (@("-File",
(Join-Path $PSScriptRoot $MyInvocation.MyCommand)) + $args)
exit
}
### Put the remainder of the scipt here ###
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment