Skip to content

Instantly share code, notes, and snippets.

@IISResetMe
Created December 30, 2014 15:40
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save IISResetMe/36ef331484a770e23a81 to your computer and use it in GitHub Desktop.
Save IISResetMe/36ef331484a770e23a81 to your computer and use it in GitHub Desktop.
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
Copy link

arricc commented Jul 10, 2018

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

@fluttr
Copy link

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.

@JAProvencher
Copy link

This is old, but instead of $MachineSID = ($p = $LocalAccountSID -split "-")[0..($p.Length-2)]-join"-", you can use $MachineSID = $LocalAccountSid.Substring(0,$LocalAccountSid.LastIndexOf('-')). Same output and IMO a cleaner process.

@IISResetMe
Copy link
Author

@JAProvencher yeah, could definitely be written more conscisely, today I'd probably opt for $LocalAccountSid -replace '-[^-]+$' :)

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