Recently, I was creating a PowerShell script in which it turned out that I needed to use SIDs to uniquely identify an object. There might be other ways to uniquely identify an object/account but the SID just seemed easiest.

One of the things I wanted to achieve is to know what object belonged to a specific SID and the other way around. Since I didn’t know if the SID belonged to a user or to a group, I couldn’t rely on the Get-ADUser cmdlet and filter based on the SID:

Get-ADUser –Filter {SID –eq <sid>}

If the SID would belong to a group, the cmdlet above wouldn’t return anything. I could use an if-else statement, but that still would not guarantee a correct result. Furthermore, every time I fire the script I risk that the script has to go through multiple loops which would probably negatively influence the script’s performance.

Luckily, PowerShell has some built-in features that allow you to “convert” an SID into an account (or the other way around). Think about it for a minute: since you already have the SID, you know what account it belongs to. You just need to go and fetch it. There’s no need to loop through all objects and see if a match can be found…

How does it work then? First, we need to create a new object either from the SID class or from the NTAccount class. Afterwards, we fetch the account name where the SID belongs to using the Translate method:

$object = New-Object System.Security.Principal.SecurityIdentifier (“S-1-5-21-1464570058-3711975594-539085127-1210”)
$result = $object.Translate([System.Security.Principal.NTAccount])
$result.Value

This is how it looks like if we run it from PowerShell:image

We can also make it work the other way around (from account name to SID):

$object = New-Object System.Security.Principal.NTAccount(“exblog”,”mvanhorenbeeck”)
$result = $object.Translate([System.Security.Principal.SecurityIdentifier])
$result.Value

image

Note: this approach unfortunately does not work for computer accounts. It can only be used for users or groups.