Private/Helpers/Test-AdminRights.ps1
|
function Test-AdminRights { <# .SYNOPSIS Tests if the provided credentials have AD Admin or OU Admin rights. .DESCRIPTION The Test-AdminRights function checks if the user associated with the provided credentials is a member of AD Admin groups or has OU Admin rights. .PARAMETER None This function uses the centralized $script:adminCreds for credentials. .EXAMPLE $adminRights = Test-AdminRights #> # Ensure that $script:adminCreds is set if (-not $script:adminCreds) { Write-Log "Admin credentials not found. Please run Get-DomainReport first." -Level Error return @{ IsADAdmin = $false IsOUAdmin = $false Username = "Unknown" } } $Username = $script:adminCreds.UserName $Credential = $script:adminCreds $adminStatus = @{ IsADAdmin = $false IsOUAdmin = $false Username = $Username } # Prepare base parameters for queries $userParams = @{ Identity = $Username; ErrorAction = 'Stop'; Credential = $Credential } # Check AD Admin status (Domain/Enterprise Admin membership) try { $user = Get-ADUser @userParams -Properties MemberOf if ($user -and $user.MemberOf) { $groupParams = @{ ErrorAction = 'Stop'; Credential = $Credential } $adminGroups = $user.MemberOf | Get-ADGroup @groupParams | Select-Object -ExpandProperty Name if ($adminGroups -match "Domain Admins|Enterprise Admins|Schema Admins|BUILTIN\\Administrators") { $adminStatus.IsADAdmin = $true } } } catch { Write-Warning "Error checking AD Admin status for $Username : $_" } # Check OU Admin status (looking for OU-level permissions) try { $ouParams = @{ Filter = '*'; ErrorAction = 'Stop'; Credential = $Credential } $ouList = Get-ADOrganizationalUnit @ouParams -Properties DistinguishedName foreach ($ou in $ouList) { # Get ACL without credential (Get-ACL AD: doesn't support credentials directly) # This checks under the provided credential context $acl = Get-Acl "AD:$($ou.DistinguishedName)" $aclMatches = $acl.Access | Where-Object { $_.IdentityReference -like "*$Username*" -and $_.ActiveDirectoryRights -match "CreateChild|DeleteChild|WriteProperty" } if ($aclMatches) { $adminStatus.IsOUAdmin = $true break } } } catch { Write-Warning "Error checking OU Admin status for $Username : $_" } # Return results return $adminStatus } |