ConvertTo-sthSID.ps1

<#
.synopsis
Function for converting byte array into string SID.
 
.description
 
When you query the Active Directory for computer or user object's objectSID property
by means of ADSI, for example:
 
    $User = [ADSI]"LDAP://CN=user_name,CN=Users,DC=domain_name,DC=com"
    $User.objectSID
 
you get a byte array.
 
This function converts this byte array into a string form of SID.
 
.example
$User = [ADSI]"LDAP://CN=user_name,CN=Users,DC=domain_name,DC=com"
ConvertTo-sthSID -ByteArray $User.objectSID
 
Get the user_name user object and convert its objectSID property into a string form.
 
.example
$User = [ADSI]"LDAP://CN=user_name,CN=Users,DC=domain_name,DC=com"
$User.objectSID | ConvertTo-sthSID
 
Get the user_name user object and convert its objectSID property into a string form
using pipeline.
 
.notes
Additional Information.
 
2.4.2.2 SID--Packet Representation
https://msdn.microsoft.com/en-us/library/gg465313.aspx
 
1 byte - Revision (must be 1)
1 byte - SubAuthorityCount (not included in String SID)
6 bytes - IdentifierAuthority
SubAuthorityCount * 4 bytes (32 bits) - SubAuthority
 
# $in[0] - Revision
# $in[1] - SubAuthorityCount (not included in String SID)
# $in[2..7] - IdentifierAuthority, because $in[2..6] are zeroes, actually $in[7]
# $in[8..11] - First Block of SubAuthority
# $in[12..15] - Second Block of SubAuthority
# $in[16..19] - Third Block of SubAuthority
# $in[20..23] - Fourth Block of SubAuthority
# $in[24..27] - Fifth Block of SubAuthority
#>


function ConvertTo-sthSID
{
    [CmdletBinding()]
    Param(
        # User or Computer object's objectSID property in the byte array form.
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        $ByteArray
    )

    begin
    {
        $Stream = @()
    }

    process
    {
        foreach ($Byte in $ByteArray)
        {
            $Stream += $Byte
        }
    }
    
    end
    {
        # Revision and IdentifierAuthority
        $Result = "S-{0}-{1}" -f $Stream[0], $Stream[7]

        # SubAuthority
        for ($i = 0; $i -lt $Stream[1]; $i++)
        {
            $off = $i * 4
            $Result = "$Result-{0}" -f $([int64]$Stream[8 + $off] -bor ([int64]$Stream[9 + $off] -shl 8) -bor ([int64]$Stream[10 + $off] -shl 16) -bor ([int64]$Stream[11 + $off] -shl 24))
        }
        return $Result
    }
}