سؤال

Whats the best/easiest way to test for administrative rights in a PowerShell script?

I need to write a script that requires administrative rights and want to know the best way to achieve it.

هل كانت مفيدة؟

المحلول

This is the little function I have in a security module:

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.
    #>
}

نصائح أخرى

In Powershell 4.0 you can use requires at the top of your script:

#Requires -RunAsAdministrator

Outputs:

The script 'MyScript.ps1' cannot be run because it contains a "#requires" statement for running as Administrator. The current Windows PowerShell session is not running as Administrator. Start Windows PowerShell by using the Run as Administrator option, and then try running the script again.

FYI, for those folks that have the PowerShell Community Extensions installed:

PS> Test-UserGroupMembership -GroupName Administrators
True

This cmdlet is a bit more generic in that you can test for group membership in any group.

Here it is directly:

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

Check out this url: http://blogs.technet.com/b/heyscriptingguy/archive/2011/05/11/check-for-admin-credentials-in-a-powershell-script.aspx

I didn't test it but the summary seems to state what you are looking for: "Learn how to check for administrative credentials when you run a Windows PowerShell script or command."

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top