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

res*_*101 18 sysadmin powershell admin-rights

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

我需要编写一个需要管理权限的脚本,并希望了解实现它的最佳方法.

And*_*ndi 22

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

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


edd*_*ves 17

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

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

输出:

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


Kei*_*ill 5

仅供参考,对于那些安装了PowerShell 社区扩展的人

PS> Test-UserGroupMembership -GroupName Administrators
True
Run Code Online (Sandbox Code Playgroud)

此 cmdlet 更通用,因为您可以测试任何组中的组成员身份。


Jud*_*red 5

这是直接的:

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

  • 不错的单线。 (3认同)