Skip to content

Instantly share code, notes, and snippets.

@robderickson
Last active June 20, 2023 16:16
Show Gist options
  • Save robderickson/013ac0603e66ffa0e97b3841bda26ca3 to your computer and use it in GitHub Desktop.
Save robderickson/013ac0603e66ffa0e97b3841bda26ca3 to your computer and use it in GitHub Desktop.
Use LDAP filter syntax to get AD objects with the ActiveDirectory module installed.
function Get-RTADObject {
[CmdletBinding()]
param(
[string]$LdapFilter,
[string]$ComputerName,
[PSCredential]$Credential
)
process {
if ($ComputerName) {
$bindingServer = $ComputerName
} else {
$bindingServer = [adsi]::new().distinguishedName
}
if ($Credential) {
$binding = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($bindingServer)", $Credential.UserName, $Credential.GetNetworkCredential().Password)
} else {
$binding = New-Object System.DirectoryServices.DirectoryEntry("LDAP://$($bindingServer)")
}
$directorySearcher = New-Object System.DirectoryServices.DirectorySearcher($binding)
$directorySearcher.SearchScope = 'subtree'
$directorySearcher.PageSize = 1000
$directorySearcher.SizeLimit = 100000
$directorySearcher.Filter = $LdapFilter
$result = $directorySearcher.FindAll()
foreach ($item in $result) {
$object = @{}
$item.Properties.Keys | ForEach-Object {
$object[$_] = $item.Properties[$_][0]
}
[pscustomobject]$object
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment