Skip to content

Instantly share code, notes, and snippets.

@jasonsedwards
Created February 21, 2012 13:44
Show Gist options
  • Save jasonsedwards/1876643 to your computer and use it in GitHub Desktop.
Save jasonsedwards/1876643 to your computer and use it in GitHub Desktop.
Get OU of User in Active Directory from Windows Powershell
# Function Find users OU
function getADGroup { param([string]$adfindtype, [string]$cName)
# Create A New ADSI Call
$root = [ADSI]''
# Create a New DirectorySearcher Object
$searcher = new-object System.DirectoryServices.DirectorySearcher($root)
# Set the filter to search for a specific CNAME
$searcher.filter = "(&(objectClass=$adfindtype) (sAMAccountName=$cName))"
# Set results in $adfind variable
$adfind = $searcher.findall()
# If Search has Multiple Answers
if ($adfind.count -gt 1) {
$count = 0
foreach($i in $adfind)
{
# Write Answers On Screen
write-host $count ": " $i.path
$count += 1
}
# Prompt User For Selection
$selection = Read-Host "Please select item: "
# Return answer using a combintaion of substring, indexOf & slice methods
$s = $adfind[$selection].path
$s = $s.substring($s.indexOf("OU=")+3).split(",")
return $s[0]
}
# Return answer using a combintaion of substring, indexOf & slice methods
$s = $adfind[0].path
$s = $s.substring($s.indexOf("OU=")+3).split(",")
return $s[0]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment