Friday, November 16, 2018

Fun with bitmask math

I had fun today working on queries against Active Directory userAccountControl. In cases like mine where you have 514 and 546 for enabled and disabled accounts, I wanted to check which bit is set.
so 2 to the power of 2 is set if the account is disabled.


see here for more values to play with https://jackstromberg.com/2013/01/useraccountcontrol-attributeflag-values/

the bitmask.ps1 script gives me all the bits set

param([int]$value=2147483647)

clear
[int]$i=0
$hexvalue = '{0:X}' -f $value
$bitmask = [convert]::tostring($value,2)
write-host "hex original value is 0x$($hexvalue)"
write-host "dec original value is $value"
write-host "bin original value is $bitmask"

do {

$valcheck = [math]::pow(2,$i)

if ( $value -band $valcheck) { write-host "hit: 2 to the power of $i = $valcheck"}

$i++
} until ($i -eq 31)
write-host "info: max tested to 2 to the power of 30, the max value for a int32 value"




In my case, I have userAccountControl as an integer value in a SQL database and I can run the following query to find all objects which are disabled, regardless if it is 514 or 546

select cn, useraccountcontrol
from [dbo].[domain.com_users]
where useraccountcontrol & 2 = 2