Skip to content

Instantly share code, notes, and snippets.

@bill-long
Last active April 29, 2021 15:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bill-long/d77d2465aca3c04f873f1b5d2664c8d3 to your computer and use it in GitHub Desktop.
Save bill-long/d77d2465aca3c04f873f1b5d2664c8d3 to your computer and use it in GitHub Desktop.
<#
.SYNOPSIS
Searches the forest for a SID match in objectSid, sidHistory, or msExchMasterAccountSid.
.EXAMPLE
PS C:\> .\Find-Sid.ps1 -Sid "S-1-5-21-408950988-2208783158-1246939005-2158"
Shows all objects matching the specified SID.
#>
[CmdletBinding()]
param (
[Parameter(Mandatory = $true, ValueFromPipeline = $true)]
[string]
$Sid
)
process {
$securityIdentifier = New-Object System.Security.Principal.SecurityIdentifier($Sid)
$bytes = New-Object byte[] $securityIdentifier.BinaryLength
$securityIdentifier.GetBinaryForm($bytes, 0)
$byteString = ""
foreach ($byte in $bytes) {
$byteString += "\" + $byte.ToString("X2")
}
$forest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
$gc = $forest.FindGlobalCatalog()
$searcher = $gc.GetDirectorySearcher()
$searcher.Filter = "(|(objectSid=$byteString)(sidHistory=$byteString)(msExchMasterAccountSid=$byteString))"
$results = $searcher.FindAll()
foreach ($result in $results) {
$dn = $result.Properties["distinguishedName"][0].ToString()
$searcher.SearchRoot = $result.GetDirectoryEntry()
$searcher.SearchScope = "Base"
$searcher.Filter = "(objectSid=$byteString)"
$objectSidMatch = ($null -ne $searcher.FindOne())
$searcher.Filter = "(sidHistory=$byteString)"
$sidHistoryMatch = ($null -ne $searcher.FindOne())
$searcher.Filter = "(msExchMasterAccountSid=$byteString)"
$masterAccountSidMatch = ($null -ne $searcher.FindOne())
[PSCustomObject]@{
DistinguishedName = $dn
ObjectSidMatch = $objectSidMatch
SidHistoryMatch = $sidHistoryMatch
MasterAccountSidMatch = $masterAccountSidMatch
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment