检测 PowerShell 是否以管理员身份运行

Boo*_*ang 55 powershell

如何在脚本中判断 PowerShell 是否以管理员权限运行?

我需要知道,因为我正在尝试运行一个需要能够打开受保护端口的程序。

Bil*_*art 83

([Security.Principal.WindowsPrincipal] `
  [Security.Principal.WindowsIdentity]::GetCurrent() `
).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
Run Code Online (Sandbox Code Playgroud)

这将检索当前的 Windows 身份并返回$true当前身份是否具有管理员角色(即,正在运行提升)。

  • 虽然接受的答案是正确的,但这个答案要清楚得多,尤其是对于六个月后可能会阅读您的脚本的人。 (14认同)

edd*_*ves 58

在 Powershell 4.0 中,您可以在脚本顶部使用requires

#Requires -RunAsAdministrator
Run Code Online (Sandbox Code Playgroud)

输出:

脚本“MyScript.ps1”无法运行,因为它包含以管理员身份运行的“#requires”语句。当前 Windows PowerShell 会话未以管理员身份运行。使用以管理员身份运行选项启动 Windows PowerShell,然后再次尝试运行脚本。

  • 如果您想要一个在不由管理员运行的情况下退出的函数怎么办? (2认同)
  • @KolobCanyon - 您只能提升 PowerShell _process_;您无法提升单个_功能_。这就是为什么“#Requires -RunAsAdministrator”很有用:如果您没有提升权限,它会阻止_整个脚本_运行。 (2认同)

小智 54

[bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")
Run Code Online (Sandbox Code Playgroud)

分解它的作用:

  • [bool]- 将最终结果转换为bool.
  • [System.Security.Principal.WindowsIdentity]::GetCurrent()- 检索WindowsIdentity当前正在运行的用户的 。
  • (...).groups- 访问groups身份的属性以找出身份所属的用户组。
  • -match "S-1-5-32-544"检查是否groups包含管理员组的众所周知的 SID,只有在使用“以管理员身份运行”时,身份才会包含它。

  • 我更喜欢下面@Bill_Stewart 的答案,因为它没有魔法字符串。 (7认同)
  • 而不是仅仅发布一行代码,你能解释一下它的作用吗?如有必要,这有助于未来的访问者理解和适应它。 (2认同)
  • 而不是使用 `-match` 和类型转换:`[Security.Principal.WindowsIdentity]::GetCurrent().Groups -contains 'S-1-5-32-544'` (2认同)