Skip to content

Instantly share code, notes, and snippets.

@IISResetMe
Created December 30, 2014 15:40
Show Gist options
  • 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
}
}
@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