Created
December 30, 2014 15:40
-
-
Save IISResetMe/36ef331484a770e23a81 to your computer and use it in GitHub Desktop.
PsGetSid local machine SID implementation in PowerShell
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@JAProvencher yeah, could definitely be written more conscisely, today I'd probably opt for
$LocalAccountSid -replace '-[^-]+$'
:)