Skip to content

Elevate current script to run at admin level

Sometime it is nice to be able to elevate a script to admin level without manually doing so.

The script below tries to elevate itself to be run as administrator and the user running it must be a member of the Administrator role on the machine running the script.

# Check and run the script as administrator if possible
function Test-Admin {
  $currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())

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

# This line will only be executed if elevation is successful, and it's here the rest of your script starts...
Write-Output "Successfully elevated script and is now running with full privileges..."