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 | |
} | |
} |
@arricc, your solution would work only on powershell 5.1+ which has Get-LocalUser comandlet. There are still a lot of machines without it.
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.
@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
This is faster than using WMI:
$LocalAccountSID = Get-LocalUser |Select-Object -First 1 -ExpandProperty SID