Running Script with Full Privileges

by Oct 10, 2011

On UAC-enabled systems, to make sure a script is running with full admin privileges, add this code at the beginning of your script:

param([switch]$Elevated)

function Test-Admin {
  $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
  $currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}

if ((Test-Admin) -eq $false)  {
  if ($elevated) {
    # tried to elevate, did not work, aborting
  } else {
    Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
  }
  exit
}

'running with full privileges'

Twitter This Tip!
ReTweet this Tip!