Get Users SID with PowerShell

What is a User SID? It is user’s unique identifier, usually used in application to relate to a user in a unique way. Microsoft defines SID in the following way:

A data structure of variable length that identifies user, group, and computer accounts. Every account on a network is issued a unique SID when the account is first created. Internal processes in Windows refer to an account’s SID rather than the account’s user or group name.

Applications as TFS, MDS, etc use SID to relate to a user in their databases. For various reasons you may need to retrieve the SID for a given user in order to perform the desired operation. There are multiple ways of obtaining it, and what I do often see is leveraging the ActiveDirectory module in order to retrieve such a simple metric. Although ActiveDirectory module is a powerful it is an overkill for this particular task.
There is a much simpler way to retrieve it and that is by leveraging the .Net classes. Following is a call packed in a cmdlet.

function Get-UserSid
{
    [CmdletBinding()]
    param
    (
        [Parameter(Mandatory = $true)] [string]$Username
    )
    BEGIN
    {
        Write-Verbose "Entering script $($MyInvocation.MyCommand.Name)"
        Write-Verbose "Parameter Values"
        $PSBoundParameters.Keys | ForEach-Object { Write-Verbose "$_ = '$($PSBoundParameters[$_])'" }
    }
    PROCESS
    {
        if ($Username.Contains("\"))
        {
            $dl = $Username -split "\\"
        
            $domain = $dl[0]
            $user = $dl[1]

            $objUser = New-Object System.Security.Principal.NTAccount($domain, $user)
            $strSID = $objUser.Translate([System.Security.Principal.SecurityIdentifier]) 
            
            return $strSID.Value
        }
        else
        {
            throw "Username not in down-level logon name format (DOMAIN\UserName)."
        }
    }
    END { }
}

In case your computer is not part of a domain, you can just pass in as the domain parameter the host name.

This kind of information is relatively easy to find, I still wrote this as a reminder for myself.

Still, I hope it can help someone.