Detecting and Launching PowerShell with Elevated Administrator Rights

Here is a good reference on detecting whether a PowerShell script is currently running with Administrator rights, and relaunching with elevated permissions if not.

Courtesy of Bruno Saille’s JEA Helper Tool 2.0: https://gallery.technet.microsoft.com/JEA-Helper-Tool-20-6f9c49dd


########################################################################################
#Make sure we run elevated, or relaunch as admin
########################################################################################


$CurrentScriptDirectory = $PSCommandPath.Substring(0,$PSCommandPath.LastIndexOf(“\”))
Set-Location $CurrentScriptDirectory


    #Thanks to http://gallery.technet.microsoft.com/scriptcenter/63fd1c0d-da57-4fb4-9645-ea52fc4f1dfb
     $IsAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] “Administrator”)
         if (-not $IsAdmin) 
         { 
             try
             { 
                 $ScriptToLaunch = (Get-Location -PSProvider FileSystem).Path + “\JEAHelperTool.ps1”
                 $arg = “-file `”$($ScriptToLaunch)`””
                 write-host -ForegroundColor yellow “[“(date -format “HH:mm:ss”)”] WARNING : This script should run with administrative rights – Relaunching the script in elevated mode in 3 seconds…”
                 start-sleep 3
                 Start-Process “$psHome\powershell.exe” -Verb Runas -ArgumentList $arg -ErrorAction ‘stop’
             }
             catch
             {
                 write-host -ForegroundColor red “[“(date -format “HH:mm:ss”)”] Error : Failed to restart script with administrative rights – please make sure this script is launched elevated.” 
                 break              
             }
             exit
         }
         else
         {
         write-host -ForegroundColor gray “[“(date -format “HH:mm:ss”)”] We are running in elevated mode, we can proceed with launching the tool.”
         }

category:

Leave a Reply