Powershell – Methods of acquiring admin privileges when working with scripts

Here are a few ways to acquire (prompt for) admin privileges when using PowerShell.

1. In-Script (best way IMO, if it ALWAYS needs to run as admin):

# 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
   {
   # We are not running "as Administrator" - so relaunch as administrator
   # 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";
   # Start the new process
   [System.Diagnostics.Process]::Start($newProcess);
   # Exit from the current, unelevated, process
   exit
   }

NOTE: If execution policy changes are needed, replace the arguments with the following (if erroring out and closing, add “-noexit”):

$newProcess.Arguments = '-ExecutionPolicy bypass -File "' +
							$script:MyInvocation.MyCommand.Path + '"'

Sauce

3. Within PowerShell (or another script):

Start-Process "$psHome\powershell.exe" -verb runas -ArgumentList "-file C:\scripts\script.ps1"

…also run any application as admin with this…
Start-Process cmd -verb runas
Start-Process notepad.exe -verb runas

3. With a .lnk file:

  1. Right Click your PowerShell script file and choose Create shortcut
  2. Name it as you like…
  3. Right-click the shortcut and click Properties
  4. Add powershell.exe -file at the beginning of the Target field
  5. Go to the Shortcut tab
  6. Click Advanced
  7. Check the Run as Administrator box
  8. Click OK
  9. Profit.