Home HowTo Security Test Administrator Privileges

Test Administrator Privileges

This is how you find out whether your script runs with full administrative privileges:


function Test-Admin
  $wid = [System.Security.Principal.WindowsIdentity]::GetCurrent()
  $prp = New-Object System.Security.Principal.WindowsPrincipal($wid)
  $adm = [System.Security.Principal.WindowsBuiltInRole]::Administrator

  Test-Admin returns $true if full Admin privileges are enabled, else $false

Test-Admin does not check your group membership. Instead, it looks at your current access token. This is why this function always reports accurate results, even with User Account Control. It does not care why you have certain privileges. It just checks if you have them.

The result will look like this:

PS> Test-Admin


In this case, the user running the function did not currently have Administrator privileges – either because the user is no Administrator, or because the system runs User Account Control, and PowerShell did not run elevated.

You can now make decisions based on this:


if (Test-Admin)
  'You are Administrator!'
  'You do not have Administrator privileges.'

  Output a message telling whether or not you are an Admin

Or, if you know your script requires Administrator privileges, you can check these prerequisites and act in a civilized way rather than running into privilege problems:


if ((Test-Admin) -eq $false)
  Write-Warning 'You need Administrator privileges to run this.'
  # Abort the script
  # this will work only if you are actually running a script
  # if you did not save your script, the ISE editor runs it as a series
  # of individual commands, so break will not break then.

'When you got to this point, you know the script has Admin privileges.'

  Make sure a script runs elevated

When a user runs the script and has no Admin privileges, the output will look similar to this:

WARNING: You need Administrator privileges to run this.