Detect If Running as Administrator with or Without Elevated Privileges

Detect if running with elevated privileges? (domain administrator accounts included)

You need to pass the domain values to IsInRole:

// DOMAINNAME\Domain Admins RID: 0x200
bool isElevated = principal.IsInRole(WindowsBuiltInRole.Administrator)
|| principal.IsInRole(0x200);

How to detect if CMD is running as Administrator/has elevated privileges?

ADDENDUM: For Windows 8 this will not work; see this excellent answer instead.


Found this solution here: http://www.robvanderwoude.com/clevertricks.php

AT > NUL
IF %ERRORLEVEL% EQU 0 (
ECHO you are Administrator
) ELSE (
ECHO you are NOT Administrator. Exiting...
PING 127.0.0.1 > NUL 2>&1
EXIT /B 1
)

Assuming that doesn't work and since we're talking Win7 you could use the following in Powershell if that's suitable:

$principal = new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())
$principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)

If not (and probably not, since you explicitly proposed batch files) then you could write the above in .NET and return an exit code from an exe based on the result for your batch file to use.

How to determine if user is an Administrator, even if non-elevated

There is a Win32 API GetTokenInformation that can be used to check the current token. If the returned token is a split token, it probably is an administrator user that is running i non elevated mode.

GetTokenInformation has an output parameter tokenInformation which takes one of three values:

  • TokenElevationTypeDefault = 1
  • TokenElevationTypeFull = 2
  • TokenElevationTypeLimited = 3

A value of TokenElevantionTypeLimited indicates that the user is running with a split token with limited privileges. When elevated the TokenElevationTypeFull value is returned. Non-admin user has a value of TokenElevationTypeDefault.

There is a complete code example for C# at http://www.davidmoore.info/2011/06/20/how-to-check-if-the-current-user-is-an-administrator-even-if-uac-is-on/

C# Check if run as administrator

Try this

public static bool IsAdministrator()
{
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}

This looks functionally the same as your code, but the above is working for me...

doing it functionally, (without unnecessary temp variables) ...

public static bool IsAdministrator()
{
return (new WindowsPrincipal(WindowsIdentity.GetCurrent()))
.IsInRole(WindowsBuiltInRole.Administrator);
}

or, using expression-bodied property:

public static bool IsAdministrator =>
new WindowsPrincipal(WindowsIdentity.GetCurrent())
.IsInRole(WindowsBuiltInRole.Administrator);

How to check if the program was ran as an administator?

UACHelper worked great, so this question is solved!



Related Topics



Leave a reply



Submit