Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
PsGetSid local machine SID implementation in PowerShell
function Get-MachineSID
{
param(
[switch]
$DomainSID
)
# Retrieve the Win32_ComputerSystem class and determine if machine is a Domain Controller
$WmiComputerSystem = Get-WmiObject -Class Win32_ComputerSystem
$IsDomainController = $WmiComputerSystem.DomainRole -ge 4
if($IsDomainController -or $DomainSID)
{
# We grab the Domain SID from the DomainDNS object (root object in the default NC)
$Domain = $WmiComputerSystem.Domain
$SIDBytes = ([ADSI]"LDAP://$Domain").objectSid |%{$_}
New-Object System.Security.Principal.SecurityIdentifier -ArgumentList ([Byte[]]$SIDBytes),0
}
else
{
# Going for the local SID by finding a local account and removing its Relative ID (RID)
$LocalAccountSID = Get-WmiObject -Query "SELECT SID FROM Win32_UserAccount WHERE LocalAccount = 'True'" |Select-Object -First 1 -ExpandProperty SID
$MachineSID = ($p = $LocalAccountSID -split "-")[0..($p.Length-2)]-join"-"
New-Object System.Security.Principal.SecurityIdentifier -ArgumentList $MachineSID
}
}
@arricc

This comment has been minimized.

Copy link

@arricc arricc commented Jul 10, 2018

This is faster than using WMI:
$LocalAccountSID = Get-LocalUser |Select-Object -First 1 -ExpandProperty SID

@fluttr

This comment has been minimized.

Copy link

@fluttr fluttr commented May 8, 2020

@arricc, your solution would work only on powershell 5.1+ which has Get-LocalUser comandlet. There are still a lot of machines without it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment