Wednesday, July 15, 2015

Convert a SID to or from a user account or group account name in PowerShell

If you have a SID as a string, and you need to know which user account or group account it belongs to, you can convert it in two simple steps. First use dynamic type conversion to convert it to a SecurityIdentifier object. Then use the .Translate() method of the SecurityIdentifier object to convert it to a Security Principal NTAccount, whose .Value property contains the account name. The result will be a string in the form domain\user.

001
002
$SID = 'S-1-5-21-314159-2658589793-314159265-3589'
$AccountName = ( [Security.Principal.SecurityIdentifier]$SID ).Translate( [Security.Principal.NTAccount] ).Value

To go the other way, we just reverse it.

001
002
$AccountName = 'contoso\tcurwick'
$SID = ( [Security.Principal.NTAccount]$AccountName ).Translate( [Security.Principal.SecurityIdentifier] ).Value

The full path to the referenced classes are [System.Security.Principal.SecurityIdentifier] and [System.Security.Principal.NTAccount], but System. is the default namespace and PowerShell automatically look there for things, so we can remove it for brevity.

This is a shortened version of code stolen from Michael Pedersen's Blog.