管理员权限的通用测试

Gor*_*don 3 powershell

是否有单一的保证方法来测试当前用户是否具有管理员权限?我试过这个

$isAdmin = (new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole("Administrators")
Run Code Online (Sandbox Code Playgroud)

只要 Windows 最初是用英文安装的,它就可以工作。如果 Windows 以西班牙语安装,您必须测试 Administra d ors。还有一些其他语言的工作方式类似。我的第一个想法是测试所有可能的拼写,但如果有一些简单、优雅和万无一失的东西,那将是我的首选。

Avs*_*lom 5

您正在调用方法的String定义IsInRole,这就是您在不同语言中遇到问题的原因。

如果您查看IsInRoleOverLoadDefinitions,您会看到第一个 Defintion 是 a String,它是您在代码中调用的定义

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)
Run Code Online (Sandbox Code Playgroud)

这种基于字符串的重载与NET LOCALGROUP Administrators命令具有相同的缺点,它依赖于不同操作系统语言中不同的组名称。

要解决此问题,请使用System.Security.Principal.WindowsBuiltInRoleOverLoadDefinition:

$role = [System.Security.Principal.WindowsBuiltInRole] "Administrator"
Run Code Online (Sandbox Code Playgroud)

并检查此角色:

$isAdmin = (new-object System.Security.Principal.WindowsPrincipal([System.Security.Principal.WindowsIdentity]::GetCurrent())).IsInRole($role)
Run Code Online (Sandbox Code Playgroud)

这样你就不需要关心不同的操作系统语言

*要获取所有可用的 WindowsBuiltInRoles:

[System.Enum]::GetValues([System.Security.Principal.WindowsBuiltInRole])
Run Code Online (Sandbox Code Playgroud)