PowerShell: check whether the current user is a member of Domain Admins

# short snippet to check whether the currently login user is a domain admin
$CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$WindowsPrincipal = New-Object System.Security.Principal.WindowsPrincipal($CurrentUser)
if($WindowsPrincipal.IsInRole("Domain Admins")){
Write-Host "$($currentUser.Name) is a Domain Admin"
}else{
Write-Host "$($currentUser.Name) not a Domain Admin."
}
# 1-liner to check members of the "Domain Admins" Group
Get-ADGroupMember -Identity "Domain Admins" -Recursive | %{Get-ADUser -Identity $_.distinguishedName} | Where-Object {$_.Enabled -eq $True} | Select Name
# 1-liner to check members of the "Enterprise Admins" Group
Get-ADGroupMember -Identity "Enterprise Admins" -Recursive | %{Get-ADUser -Identity $_.distinguishedName} | Where-Object {$_.Enabled -eq $True} | Select Name
# Function to check whether a given username matches the list of Domain Admins
function validateDomainAdmin{
param (
[string]$username
)
$domainAdmins=Get-ADGroupMember -Identity "Domain Admins" -Recursive | %{Get-ADUser -Identity $_.distinguishedName} | Where-Object {$_.Enabled -eq $True}
$matchedAdmin=$username -in $domainAdmins.SamAccountName
if($matchedAdmin){
Write-Host "$username is a Domain Admin"
}else{
Write-Host "$username not a Domain Admin."
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *