If you don't have the AD-Module installed, you can also use this. I found this very useful when I ran scripts where I needed AD-Information, but didn't have the AD-Module installed. :
$strFilter = "(&(objectCategory=User)(samAccountName=$env:username))"
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.Filter = $strFilter
$objPath = $objSearcher.FindOne()
$objUser = $objPath.GetDirectoryEntry()
objUser.distinguishedName
$ADVal = [ADSI]"LDAP://
WorkOU = $ADVal.Parent
$WorkOU
Now $WorkOU would return a string like this LDAP://OU=userou,OU=userou2,DC=internal,DC=domain,DC=com which you can filter any way you want.
If you don't have the AD-Module installed, you can also use this. I found this very useful when I ran scripts where I needed AD-Information, but didn't have the AD-Module installed. :
$strFilter = "(&(objectCategory=User)(samAccountName=$env:username))"
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.Filter = $strFilter
$objPath = $objSearcher.FindOne()
$objUser = $objPath.GetDirectoryEntry()
objUser.distinguishedName
$ADVal = [ADSI]"LDAP://
WorkOU = $ADVal.Parent
$WorkOU
Now $WorkOU would return a string like this LDAP://OU=userou,OU=userou2,DC=internal,DC=domain,DC=com which you can filter any way you want.
This works for me:
$user = Get-ADUser -Identity [USERNAME] -Properties CanonicalName
$userOU = ($user.DistinguishedName -split ",",2)[1]
Source: http://itknowledgeexchange.techtarget.com/powershell/discovering-a-users-ou/
Can anyone see any issues with doing it this way.
Yes, I see two immediate problems that might arise from your current approach.
1. Escaped commas
Consider an OU with a comma in its name, like: OU=Users\, Admin,DC=corp,DC=example
Your use of string.Split() won't care about the escape sequence and you end up with:
Admin,DC=corp,DC=example
Use the -split regex operator with a lookbehind to make sure you ignore escaped commas:
$parts = $user.DistinguishedName -split '(?<!\\),'
2. Portability
Your code assumes that the NC part of the DN (eg. DC=example,DC=com), will always be just 2 labels wide. This means your code will fail if you use it in scripts you might want to reuse in other domains/environments.
I would grab each part, from right-to-left until I find one without the DC RDN prefix:
$topParts = foreach($part in $parts[-1..-$parts.Length]){
$part
if($part -notlike 'DC=*'){
break
}
}
# Remember to reverse the RDNs again
$path = $topParts[-1..-$topParts.Length] -join ','
In my opinion it is simpler to use Pathname COM object and simply ask for the parent of the DN. You can put this in a while loop to get the hierarchy of the object. Example using my ADName module:
$dn = Get-ADUser user | Select-Object -ExpandProperty DistinguishedName
$parent = $dn | Get-ADName -Format Parent
while ( $parent -like "OU=*" ) {
$parent
$parent = $parent | Get-ADName -Format Parent
}
Example output:
OU=Level 3,OU=Level 2,OU=Level 1,DC=fabrikam,DC=com
OU=Level 2,OU=Level 1,DC=fabrikam,DC=com
OU=Level 1,DC=fabrikam,DC=com
From my generic AD export script:
$OU = "OU=employees,DC=domain,DC=local" # OU you want to filter/export
$CSVname = "c:\scripts\active_directory\CurrentStaff.csv" #Name and location of the export file
Import-Module ActiveDirectory #Imports AD module
#This search will give you Office field, Lastname, Firstname, and email address
Get-ADUser -SearchBase $OU -Filter * -Properties GivenName,Surname,EmailAddress,Office | Select GivenName,Surname,EmailAddress,Office | Export-Csv $csvname
I have it on my github that shows all the properties you can search for as well.
Hey everybody, I am looking for a way to query AD and get a report that includes the following:
First Name
Last Name
Email Address
Office
These fields all exist on the general tab of the users properties in AD.
Thank you all in advance for your help.
@raji7580 @powershellman8045 @ad82
I’m trying to build a script to run that searches for AD user accounts that are configured for Password_not_required (544) and change them to password_req (512). I cant quite figure out the section on the searchbase as I want to limit the search to 2 OU’s only, I have put these in a variable $OU and referenced it but the script fails. Any help would be appreciated.
log file
if ($logfile -eq $null)
{
$logfile = “C:\test\ADUsersChangedPWNOTREQD.txt”
New-Item $logfile -ItemType File
}
#OU Information
$ous = ‘OU=Standard users,DC=x1,DC=contoso,DC=com’,‘OU=Standard users,DC=x2,DC=contoso,DC=com’
set flag PasswordNotRequired to false
$UsersNoPwdRequired = Get-ADUser -Properties Name,distinguishedname,useraccountcontrol,objectClass -SearchBase $ous -LDAPFilter “(&(userAccountControl:1.2.840.113556.1.4.803:=32)(!(|(userAccountControl:1.2.840.113556.1.4.803:=2)(userAccountControl:1.2.840.113556.1.4.803:=65536)(IsCriticalSystemObject=TRUE))))”
foreach($user in $UsersNoPwdRequired )
{
Set-ADAccountControl $user -PasswordNotRequired $false
Add-Content $logfile “$User”
}
If you post code, please use the ‘Insert Code’ button. Please and thank you!
Hi, and welcome to the PowerShell forum! Don’t apologize for being a “noob” or “newbie” or “n00b.” There’s just no need – nobody will think you’re stupid, and the forums are all about asking questions. Just ask! Use a descriptive subject. Don't say "Need help" or "PowerShell Help", actually summarize what the problem is. It helps the rest of us keep track of which problem is which. Don’t post massive scripts. We’re all volunteers and we don’t have time to read all that, nor will we copy, past…

Here's an example of a very basic script I'm working on to pull some different properties of an AD user. I pulled this from a website and was wondering how I would find all of the other different (properties? variables?) that "SamaccountName" or "ObjectSid" are. For example, if I wanted to query my entire on-prem AD for all user's email address field, how would I do that? Thanks.
Hey guys, is there a way to use a list of usernames in a CSV file to get their OU location?
Hey guys, is there a way to use a list of usernames in a CSV file to get their OU location?
what list you have text or CSV? try this
$users=get-content c:\list.txt
ForEach($user in $users){
get-aduser $user |select name,DistinguishedName
}