Active Directory UserAccountControl Details

Reference: https://support.microsoft.com/en-us/help/305144/how-to-use-useraccountcontrol-to-manipulate-user-account-properties

function Get-UserAccountControlDetail
{
    [cmdletbinding()]
    PARAM(
        [int]$val
    )

    $UACflagHash = @{
        1        = 'SCRIPT'
        2        = 'ACCOUNTDISABLE'
        8        = 'HOMEDIR_REQUIRED'
        16       = 'LOCKOUT'
        32       = 'PASSWD_NOTREQD'
        64       = 'PASSWD_CANT_CHANGE'
        128      = 'ENCRYPTED_TEXT_PWD_ALLOWED'
        256      = 'TEMP_DUPLICATE_ACCOUNT'
        512      = 'NORMAL_ACCOUNT'
        2048     = 'INTERDOMAIN_TRUST_ACCOUNT'
        4096     = 'WORKSTATION_TRUST_ACCOUNT'
        8192     = 'SERVER_TRUST_ACCOUNT'
        65536    = 'DONT_EXPIRE_PASSWORD'
        131072   = 'MNS_LOGON_ACCOUNT'
        262144   = 'SMARTCARD_REQUIRED'
        524288   = 'TRUSTED_FOR_DELEGATION'
        1048576  = 'NOT_DELEGATED'
        2097152  = 'USE_DES_KEY_ONLY'
        4194304  = 'DONT_REQ_PREAUTH'
        8388608  = 'PASSWORD_EXPIRED'
        16777216 = 'TRUSTED_TO_AUTH_FOR_DELEGATION'
        67108864 = 'PARTIAL_SECRETS_ACCOUNT'
    }

    $desc = @()
    foreach($obj in ($UACflagHash.GetEnumerator() | sort name)){
        if($val -band $obj.name){
            Write-Verbose "$val bitwise and match `n$(($obj | Out-String).trim())`n"
            $desc += $UACflagHash[$obj.name]
        }
    }
    $desc -join " | "
}

#Get all AD objects that have a value for useraccountcontrol
$allobjects = get-adobject -LDAPFilter "(useraccountcontrol=*)" -prop useraccountcontrol,canonicalname,objectcategory,samaccountname
$allobjects | group useraccountcontrol | select count,name | sort count -Descending

#Add custom noteproperty containing delimted useraccountcontrol translation
$allobjects | % {Add-Member -InputObject $_ -MemberType NoteProperty -Name 'UACdetail' -Value (Get-UserAccountControlDetail $_.useraccountcontrol) -Force}
$allobjects | select canonicalname,samaccountname,objectclass,UACdetail,UserAccountControl | ft -a -wr 

#Get count of individual useraccountcontrol flags
$UACdetailCounts = @{}
$allobjects | % {$_.UACdetail.split('|') | % {$UACdetailCounts[$_.trim()]++}}
$UACdetailCounts.GetEnumerator() | sort value -Descending