Reputation: 6873
Is there a single guaranteed method to test if the current user has admin rights? I have tried this
$isAdmin = (new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole("Administrators")
And it works, as long as Windows was originally installed in English. If Windows is installed in Spanish you have to test for Administradors. And there are a few other languages that work similarly. My first thought is to just test for all the possible spellings, but if there is something simple, elegant and foolproof, that would be my preference.
Upvotes: 3
Views: 1565
Reputation: 8889
You are calling the String
definition of the IsInRole
Method, and this is why you have problems in different languages.
If you will look at the IsInRole
OverLoadDefinitions you'll see that the first Defintion is a String
which is the definition you are calling in your code
OverloadDefinitions
-------------------
bool IsInRole(string role)
bool IsInRole(System.Security.Principal.WindowsBuiltInRole role)
bool IsInRole(int rid)
bool IsInRole(System.Security.Principal.SecurityIdentifier sid)
bool IPrincipal.IsInRole(string role)
This string-based overload shares the same disadvantage of the NET LOCALGROUP Administrators
command, it relies on group names which are not the same in different OS Languages.
To solve this problem, use the System.Security.Principal.WindowsBuiltInRole
OverLoadDefinition:
$role = [System.Security.Principal.WindowsBuiltInRole]::Administrator
And check against this role instead:
$isAdmin = (new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole($role)
This way you don't need to care about differrent OS languages
*To get all the available WindowsBuiltInRoles:
[System.Enum]::GetValues([System.Security.Principal.WindowsBuiltInRole])
Upvotes: 6
Reputation: 54971
You can use the SID for Administrators as it's a well-known SID (static).
SID: S-1-5-32-544
Name: Administrators
Description: A built-in group. After the initial installation of the operatingsystem, the only member of the group is the Administrator account. When a computer joins a domain, the Domain Admins group is added to the Administrators group. When a server becomes a domain controller, the Enterprise Admins group also is added to the Administrators group.
$isAdmin = (new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole(([System.Security.Principal.SecurityIdentifier]"S-1-5-32-544"))
Upvotes: 1