Search PowerShellers and other PowerShell-related sites

Thursday, June 11, 2009

How to get computer SID using PowerShell

Let's start with the theory. ;)

The computer SID is stored in the HKEY_LOCAL_MACHINE\SECURITY\SAM\Domains\Account Registry subkey. This key has a value named F and a value named V. The V value is a binary value that has the computer SID embedded within it at the end of its data. This SID is in a standard format (3 32-bit subauthorities preceded by three 32-bit authority fields).

Because you can't see the SECURITY hive's contents by default (even as an administrator), you need a little trick. Use at command to schedule the startup of PowerShell. Make sure that you schedule the task as Interactive and that the Scheduler service runs in the security context of the System (aka LocalSystem) account because this account—unlike a regular user account—has privileges to view the SAM and SECURITY hives.

c:\> at TIME /interactive powershell.exe

PS> $key = Get-Item HKLM:\security\sam\domains\account
PS> $values = Get-ItemProperty $key.pspath
PS> $bytearray = $values.V
PS> New-Object System.Security.Principal.SecurityIdentifier($bytearray[272..295],0) | Format-List *

BinaryLength : 24
AccountDomainSid : S-1-5-21-796845957-602608370-839522115
Value : S-1-5-21-796845957-602608370-839522115

You can check your result with Sysinternals' PsGetSid:

PS> .\psgetsid.exe