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


Answers:


42
[bool](([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")

分解这是做什么的:

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

2
不只是发布一行代码,您能解释一下它的作用吗?如有必要,这有助于将来的访客了解和适应它。
slhck 2014年

嘘 给这个人更多的赞誉
Kolob Canyon

4
我喜欢下面的@Bill_Stewart答案,因为它没有魔力。
8DH

而不是使用-match和强制转换:[Security.Principal.WindowsIdentity]::GetCurrent().Groups -contains 'S-1-5-32-544'
TheIncorrigible1

57
([Security.Principal.WindowsPrincipal] `
  [Security.Principal.WindowsIdentity]::GetCurrent() `
).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)

这将检索当前的Windows身份,如果当前身份具有管理员角色(即正在提升权限),则返回True。


13
尽管公认的答案是正确的,但这个答案要清晰得多,尤其是对于六个月后可以阅读您的脚本的人而言。
Patrick Seymour 2014年

46

在PowerShell中4.0你可以使用需要在你的脚本的顶部:

#Requires -RunAsAdministrator

输出:

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


如果您希望某个功能在没有管理员运行的情况下退出,该怎么办?
Kolob峡谷

1
@KolobCanyon-没有像运行提升的PowerShell函数这样的事情;整个PowerShell过程是否提升。
Bill_Stewart '17

@Bill_Stewart是的,但是return如果用户不是admin,则可以:)
Kolob Canyon

1
@KolobCanyon-您只能提升PowerShell 进程;您不能提升单个功能。这就是为什么#Requires -RunAsAdministrator有用的原因:如果您没有提升权限,它将阻止整个脚本运行。
Bill_Stewart '17

@Bill_Stewart是的,在某些时候我必须使用它。
Kolob峡谷
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.