Checking if User has Admin Rights When Running a PowerShell Script

For my Active Directory documentation script, if the user requests hardware inventory for the domain controllers, the user must run the script with domain administrator credentials.  How do you determine if a script is being run with Domain Admin rights?


The following information is taken from:

Check for Admin Credentials in a PowerShell Script (Scripting Guys blog)

WindowsPrincipal.IsInRole Method (WindowsBuiltInRole) (MSDN)

WindowsPrincipal Class (MSDN)

WindowsPrincipal.IsInRole Method (MSDN)

WindowsBuiltInRole Enumeration (MSDN)

For testing if the user is in the LOCAL Administrators group:

1
2
3
4
5
6
7
8
If(([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrators"))
{
    #user is a member of local administrators
}
Else
{
    #user is not a member of local administrators
}

For testing if the user is in the Domain Admins group:

1
2
3
4
5
6
7
8
If(([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole("Domain Admins"))
{
    #user is a member of domain admins
}
Else
{
    #user is not a member of domain admins
}

Hope this helps.

Webster

2 Comments

  1. Joe Nord

    Awesome, and timely! Thanks Webster.

Comments are closed