Powershell script run as administrator / elevated mode check

If you created a Powershell script which needs administrator permissions, and you try to run it as a normal user (e.g. when simply double clicking the .ps1 file), you might see errors such as “Access denied”.

To fix this, you will need to run the Powershell script as Administrator. However this usually means you need to first open up a Powershell window as administrator, and then call the script manually. However, there is a simple trick to allow your script to run itself as administrator.

Snippet: Add elevated to Powershell script

Use the below code and paste it into your Powershell script at the top. When the Powershell script is run, this code will check if it is run as Administrator, and if not, it will re-open itself as Administrator.

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
}

Now you can simply double click / run the .ps1 script, then click OK in the UAC popup (if any) to confirm that you want to run as Administrator. Way faster!

Published
Categorized as Powershell

By Leendert de Borst

Freelance software architect with 10+ years of experience. Expert in translating complex technical problems into creative & simple solutions.

Leave a comment

Your email address will not be published. Required fields are marked *