163

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

11 Answers11

147

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.

Eddie Groves
  • 1,583
145
$currentPrincipal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
$currentPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

(from Command line safety tricks)

Wai Ha Lee
  • 113
  • 1
  • 6
gm3dmo
  • 10,587
51
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.

Shay Levy
  • 1,039
4

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
  • 141
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
}
Victor
  • 21
  • 1
2

LESS IS MORE

A bit code (Fltmc.exe).Count -eq 3 will gives True / False. Because the count always 3 in non-admin.

If ((Fltmc.exe).Count -eq 3) {'I AM U.S.E.R'} else {'I AM A.D.M.I.N'}; Pause

Using Function:

Function IsAdmin {(Fltmc.exe).Count -ne 3}

Then IsAdmin, Output True / False

source: fltmc.exe

Mr.Key7
  • 129
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
    }
1
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
Gregor y
  • 111
1
#! pwsh

function IsAdmin() {
    $identity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $principal = New-Object System.Security.Principal.WindowsPrincipal($identity)
    $isAdmin = $principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)
    return $isAdmin
}

function RestartWithAdmin()
{
    $scriptPath = Resolve-Path $Script:MyInvocation.MyCommand.Path
    # if you want debug, add '-noe' option to $arguments
    $arguments = @("-nop", "-nol", "-ex", "RemoteSigned", "-f", "$scriptPath")
    Start-Process pwsh -ArgumentList $arguments -Verb RunAs -Wait -PassThru
    exit
}

if (-not (IsAdmin)) {
    RestartWithAdmin
}

Write-Host "This line is only reach when script has administrator privilege"
Greg Askew
  • 39,132
ShortArrow
  • 111
  • 2
0

Less might be more:

[Security.Principal.WindowsIdentity]::GetCurrent().Groups -contains 'S-1-5-32-544'
  • [Security.Principal.WindowsIdentity]::GetCurrent() - Retrieves the WindowsIdentity for the currently running user.
  • (...).groups - Access the groups property of the identity to find out what user groups the identity is a member of.
  • -contains "S-1-5-32-544" returns true if groups contains the Well Known SID of the Administrators group (the identity will only contain it if “run as administrator” was used) and otherwise false.

Source: https://megamorf.gitlab.io/2020/05/26/check-if-powershell-is-running-as-administrator/

-3

Just another simple answer:

$isAdmin = (Get-Process -Name PowerShell -IncludeUserName).UserName.Contains('\Administrator')

This will return True if the current PowerShell process is running under the Administrator account.