144

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

4

7 Answers 7

127
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

(from Command line safety tricks)

4
  • 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, 2009 at 20:16
  • 3
    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 7, 2021 at 15:33
  • 3
    Single line without variable assignment: (New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) Feb 11, 2022 at 19:42
  • @gm3do Like the person asking (probably), yes I want to actually use the value like in your comment... but PowerShell says "The ampersand (&) character is not allowed." Please fix the code and place it in a code block so it isn't mangled by the site: meta.stackexchange.com/a/22189
    – Poikilos
    Jun 28, 2023 at 16:22
137

To cause your script to not run if not run as administrator:

#Requires -RunAsAdministrator

https://learn.microsoft.com/powershell/module/microsoft.powershell.core/about/about_requires

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.

Introduced in PowerShell 4.0.

5
  • 3
    Not exactly what I was looking for but still very useful. Thanks Eddie! Mar 19, 2015 at 17:31
  • 6
    This should be the accepted answer Feb 12, 2020 at 23:28
  • correkt link: docs.microsoft.com/en-us/powershell/module/… Mar 30, 2020 at 8:21
  • 1
    Neat solution, but the downside of it is if you run the script from the file explorer > right click > Run in Powershell (instead of running it from a terminal). In this case, the window blinks for half a second and the message cannot be read by the user. Feb 26, 2023 at 0:47
  • It's a neat idea but doesn't address the need where you want the script behavior to be different depending on whether it's running with admin privileges or not.
    – Dr Phil
    May 11, 2023 at 19:19
49
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.

7
  • 8
    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. Oct 17, 2014 at 19:34
  • 4
    @HolisticDeveloper, that is incorrect. If you aren't elevated, it will return false Jan 8, 2015 at 16:33
  • @charleswj81 as of now I observe the behavior that Holistic Developer describes.
    – zneak
    May 7, 2016 at 0:01
  • I don't think you need the semi colon... but that said I don't think it throws an error either Aug 4, 2018 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, 2018 at 8:03
3

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
2
  • 1
    Unfortunately, this doesn't work. If the script is not run with elevated rights, then it won't even load, and you won't see your custom error message. May 2, 2019 at 17:27
  • Thanks. I've corrected my answer above.
    – MovGP0
    May 20, 2019 at 22:49
2

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

Here is my take on it, if the script isn't run as an administrator, it reloads it and access for administrator access

if (-not (New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
# Prompt the user to elevate the script
$arguments = "& '" + $myInvocation.MyCommand.Definition + "'"
Start-Process powershell -Verb runAs -ArgumentList $arguments
exit
}
0
function Test-RunAsAdministrator{
   $script = new-item -path $env:TEMP -name 'TestElevated.ps1' -value @'
      #Requires -RunAsAdministrator
      $true
'@
   
   try{
      & $script.FullName
   }catch [System.Management.Automation.ScriptRequiresException]{
      $false
   }finally{
      remove-item $script.FullName
   }
}

This is a function wrapper for the #Requires statement, it should return:

  • $true, when run in an elevated context
  • $false, when run in a non-elevated context

Although in my current test scenarios it provides the same results as using the GetCurrent()

Admin User Non-Admin User
Elevated Proc $true N/A
Non Elevated Proc $false $false
$IsAdministrator = ([Security.Principal.WindowsPrincipal]::new(
   ($id = [Security.Principal.WindowsIdentity]::GetCurrent())
)).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
$id.dispose(); remove-variable id
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .