在PowerShell脚本中测试管理员权限?

在PowerShell脚本中测试管理员权限?,powershell,sysadmin,admin-rights,Powershell,Sysadmin,Admin Rights,在PowerShell脚本中测试管理权限的最佳/最简单的方法是什么 我需要写一个需要管理权限的脚本,并想知道实现它的最佳方法 查看此url: 我没有对它进行测试,但摘要似乎说明了您需要什么:“了解如何在运行Windows PowerShell脚本或命令时检查管理凭据。”这是我在安全模块中的一个小功能: function Test-IsAdmin { try { $identity = [Security.Principal.WindowsIdentity]::GetCur

在PowerShell脚本中测试管理权限的最佳/最简单的方法是什么

我需要写一个需要管理权限的脚本,并想知道实现它的最佳方法

查看此url:


我没有对它进行测试,但摘要似乎说明了您需要什么:“了解如何在运行Windows PowerShell脚本或命令时检查管理凭据。”

这是我在安全模块中的一个小功能:

function Test-IsAdmin {
    try {
        $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
        $principal = New-Object Security.Principal.WindowsPrincipal -ArgumentList $identity
        return $principal.IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator )
    } catch {
        throw "Failed to determine if the current user has elevated privileges. The error was: '{0}'." -f $_
    }

    <#
        .SYNOPSIS
            Checks if the current Powershell instance is running with elevated privileges or not.
        .EXAMPLE
            PS C:\> Test-IsAdmin
        .OUTPUTS
            System.Boolean
                True if the current Powershell is elevated, false if not.
    #>
}
功能测试IsAdmin{
试一试{
$identity=[Security.Principal.WindowsIdentity]::GetCurrent()
$principal=新对象Security.principal.WindowsPrincipal-ArgumentList$identity
返回$principal.IsInRole([Security.principal.WindowsBuiltInRole]::管理员)
}抓住{
throw“无法确定当前用户是否具有提升的权限。错误为:“{0}”。-f$_
}
测试伊萨明
.产出
系统布尔
如果当前Powershell已提升,则为True;否则为false。
#>
}

供参考,对于那些安装了:

PS> Test-UserGroupMembership -GroupName Administrators
True
此cmdlet更为通用,因为您可以测试任何组中的组成员身份。

此处直接显示:

$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
        [Security.Principal.WindowsBuiltInRole] "Administrator")

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

#Requires -RunAsAdministrator
产出:

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


好奇的是,这只是检查组中的用户,还是也检查他们是否使用所有特权令牌(提升)运行?@AndyArismendi如果没有提升,即使用户在启用UAC的系统上的Administrators组中,这也将返回false。这是因为进程只有一个“标准”用户令牌。如果进程被提升,则返回true。谢谢。请注意,当您将
#Requires-RunAsAdministrator
粘贴到PowerShell中的脚本顶部时,组名是本地化的,不会发生任何事情…这很好,但使用鼠标右键>Run with PowerShell只会立即关闭脚本<代码>读取主机,因为下一行没有帮助。当试图直接运行脚本时如何处理这个问题?很好的一行。