ConvertFrom-sthSID.ps1

<#
.synopsis
Function for converting string SID into byte array form.
 
.description
Function converts string form of SID into byte array,
the form that the SID is represented in Active Directory.
 
.example
ConvertFrom-sthSID -SID 'S-1-5-21-1234567890-1234567890-1234567890-1234'
 
Convert string SID into a byte array.
 
.example
'S-1-5-21-1234567890-1234567890-1234567890-1234' | ConvertFrom-sthSID
 
Convert string SID into byte array 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 ConvertFrom-sthSID
{
    [CmdletBinding()]
    Param(
        # SID in string form.
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [string[]]
        $SID
    )

    process
    {
        foreach ($s in $SID)
        {
            $SIDSplitted = $s -split '-' | Select-Object -Skip 1

            $Result = @()

            # Revision
            $Result += [byte]$SIDSplitted[0]

            # SubAuthorityCount
            $Result += [byte]$($SIDSplitted.Count - 2)

            # IdentifierAuthority
            for ($i = 0; $i -lt 5; $i++)
            {
                $Result += [byte]0
            }
            $Result += [byte]$SIDSplitted[1]

            # SubAuthority

            for ($i = 2; $i -lt $($SIDSplitted.Count); $i++)
            {
                $Result += [byte]$($SIDSplitted[$i] -band 255)
                $Result += [byte]$(($SIDSplitted[$i] -shr 8) -band 255)
                $Result += [byte]$(($SIDSplitted[$i] -shr 16) -band 255)
                $Result += [byte]$(($SIDSplitted[$i] -shr 24) -band 255)
            }

            $Result
        }
    }
}