Skip to content

Instantly share code, notes, and snippets.

@theangkko
Last active November 24, 2023 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theangkko/d4fb25c36b440b4ec854e30ffebbe91a to your computer and use it in GitHub Desktop.
Save theangkko/d4fb25c36b440b4ec854e30ffebbe91a to your computer and use it in GitHub Desktop.
Function Check-RunAsAdministrator()
{
#Get current user context
$CurrentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
#Check user is running the script is member of Administrator Group
if($CurrentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator))
{
Write-host "Script is running with Administrator privileges!"
}
else
{
#Create a new Elevated process to Start PowerShell
$ElevatedProcess = New-Object System.Diagnostics.ProcessStartInfo "PowerShell";
# Specify the current script path and name as a parameter
$ElevatedProcess.Arguments = "& '" + $script:MyInvocation.MyCommand.Path + "'"
#Set the Process to elevated
$ElevatedProcess.Verb = "runas"
#Start the new elevated process
[System.Diagnostics.Process]::Start($ElevatedProcess)
#Exit from the current, unelevated, process
Exit
}
}
#Check Script is running with Elevated Privileges
Check-RunAsAdministrator
#Read more: https://www.sharepointdiary.com/2015/01/run-powershell-script-as-administrator-automatically.html#ixzz8Hx1mAc85
Stop-Process -Name "code"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment