Reputation: 2255
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.
Upvotes: 21
Views: 20653
Reputation: 34828
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.
Upvotes: 19
Reputation: 11047
Here it is directly:
$isAdmin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator")
Upvotes: 7
Reputation: 52567
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.
#>
}
Upvotes: 23
Reputation: 201592
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.
Upvotes: 5
Reputation: 1159
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."
Upvotes: 2