112

In a PowerShell script, how can I check if I'm running with administrator privileges?

Michael Kelley
  • 1,235
  • 2
  • 9
  • 9
  • 5
    [Check for Admin Credentials in a PowerShell Script](http://blogs.technet.com/b/heyscriptingguy/archive/2011/05/11/check-for-admin-credentials-in-a-powershell-script.aspx) – KyleMit Aug 07 '15 at 18:43
  • 2
    Archived version of the link in the previous comment: https://web.archive.org/web/20150711220515/http://blogs.technet.com/b/heyscriptingguy/archive/2011/05/11/check-for-admin-credentials-in-a-powershell-script.aspx – AJM May 30 '22 at 10:51
  • Where Microsoft has currently moved it to https://devblogs.microsoft.com/scripting/check-for-admin-credentials-in-a-powershell-script/ – silicontrip Jun 09 '22 at 04:07

5 Answers5

114

In Powershell 4.0 you can use requires at the top of your script:

#Requires -RunAsAdministrator

Outputs:

The script 'MyScript.ps1' cannot be run because it contains a "#requires" statement for running as Administrator. The current Windows PowerShell session is not running as Administrator. Start Windows PowerShell by using the Run as Administrator option, and then try running the script again.

gregg
  • 597
  • 3
  • 9
  • 26
Eddie Groves
  • 1,253
  • 1
  • 9
  • 7
102
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

(from Command line safety tricks)

Chris S
  • 113
  • 4
gm3dmo
  • 9,632
  • 1
  • 40
  • 35
  • 3
    $currentPrincipal = New-Object Security.Principal.WindowsPrincipal( [Security.Principal.WindowsIdentity]::GetCurrent() ) &{ if ($currentPrincipal.IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator )) { (get-host).UI.RawUI.Backgroundcolor="DarkRed" clear-host write-host "Warning: PowerShell is running as an Administrator.`n" } – gm3dmo Dec 17 '09 at 20:16
  • 2
    This is a great solution where you are using an ancient version of powershell (in my case 3) that doesn't support "#Requires -RunAsAdministrator" – Kinetic Jun 07 '21 at 15:33
  • 3
    Single line without variable assignment: `(New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)` – Cameron Tacklind Feb 11 '22 at 19:42
42
function Test-Administrator  
{  
    $user = [Security.Principal.WindowsIdentity]::GetCurrent();
    (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)  
}

Execute the above function. IF the a result is True, the user has admin privileges.

Borek Bernard
  • 709
  • 2
  • 11
  • 21
Shay Levy
  • 929
  • 1
  • 5
  • 5
  • 7
    This only determines if the user running the script is an administrator on the machine -- and not if the script is currently being **executed with administrative privileges**. In other words, this will still return true even if the user did not use "run as administrator" to launch the command shell. – Holistic Developer Oct 17 '14 at 19:34
  • 3
    @HolisticDeveloper, that is incorrect. If you aren't elevated, it will return false – charleswj81 Jan 08 '15 at 16:33
  • @charleswj81 as of now I observe the behavior that Holistic Developer describes. – zneak May 07 '16 at 00:01
  • I don't think you need the semi colon... but that said I don't think it throws an error either – Kellen Stuart Aug 04 '18 at 18:52
  • 1
    This works for me on Win10 as of 2018. Returns False if current user account is not elevated, returns True if powershell is running elevated. – arberg Oct 16 '18 at 08:03
  • Exactly what i was searching for. – Aboodnet Oct 11 '20 at 00:15
  • Hello, 2022 chiming in with testing this in admin and non-admin shells. Returns true in the former, false in the latter for me. – orion elenzil May 17 '22 at 23:13
2

as a combination of the above answers, you can use something like the following at the begin of your script:

# todo: put this in a dedicated file for reuse and dot-source the file
function Test-Administrator  
{  
    [OutputType([bool])]
    param()
    process {
        [Security.Principal.WindowsPrincipal]$user = [Security.Principal.WindowsIdentity]::GetCurrent();
        return $user.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator);
    }
}

if(-not (Test-Administrator))
{
    # TODO: define proper exit codes for the given errors 
    Write-Error "This script must be executed as Administrator.";
    exit 1;
}

$ErrorActionPreference = "Stop";

# do something

Another method is to start your Script with this line, which will prevent it's execution when not started with admin rights.

#Requires -RunAsAdministrator
MovGP0
  • 121
  • 2
0

This will check if you are an Administrator, if not then it will reopen in PowerShell ISE as an Administrator.

Hope this helps!

    $ver = $host | select version
    if ($ver.Version.Major -gt 1)  {$Host.Runspace.ThreadOptions = "ReuseThread"}

    # Verify that user running script is an administrator
    $IsAdmin=[Security.Principal.WindowsIdentity]::GetCurrent()
    If ((New-Object Security.Principal.WindowsPrincipal $IsAdmin).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator) -eq $FALSE)
    {
      "`nERROR: You are NOT a local administrator.  Run this script after logging on with a local administrator account."
        # 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_ise";

        # 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
    }