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.

Answer from SimonS on Stack Exchange
🌐
ShellGeek
shellgeek.com › home › powershell › get aduser parent ou
Get AdUser Parent OU - ShellGeek
April 14, 2024 - Get-AdUser cmdlet gets active directory user identified by SamAccountName and gets the distinguished name of aduser. In the next command, it splits distinguishedname to get parent OU for ad object.
🌐
ServerWatch
serverwatch.com › home › guides
Using Get-ADUser Cmdlet to Report on Active Directory Users | ServerWatch
August 16, 2023 - PowerShell provides the Get-ADUser cmdlet, which can be used to fetch information about Active Directory users. The Get-ADUser cmdlet provides a number of different properties that you can combine with the Get-ADUser command to retrieve the ...
Top answer
1 of 3
2

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 ','
2 of 3
1

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
🌐
PowerShell Forums
forums.powershell.org › powershell help
List of users from a specific OU in the Activer Directory - PowerShell Help - PowerShell Forums
November 5, 2021 - I want to a list of users that is in the following OU: Example.domain.se … OU Systemaccounts <= here …OU Active Directory …OU Administrators <= here The attributes I want to list for each user are: -SamAccountName …
🌐
Spiceworks
community.spiceworks.com › programming & development
Get only user OU from Active Directory Using Powershell/CLI - Programming & Development - Spiceworks Community
February 15, 2017 - I want to get only OU of specific user. Example the command should display what OU user JOHN belongs to USERNAME = OUNAME
🌐
Spiceworks
community.spiceworks.com › programming & development
Get only user OU from Active Directory Using Powershell/CLI - #2 by bdascott - Programming & Development - Spiceworks Community
February 15, 2017 - Get-aduser username | select Distinguishedname I’ll see if i can find the correct string commands. Are you hoping to use this information as a variable for other things, or just to print it out?
🌐
Netwrix
blog.netwrix.com › 2023 › 04 › 26 › get-aduser-powershell-cmdlet-for-managing-active-directory-users
User Management via the Get-ADUser Cmdlet in PowerShell
Looking for the latest in security? Explore our blog for expert insights, actionable tips, and proven strategies to strengthen your data and identity security.
Find elsewhere
Top answer
1 of 8
4

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”
}

2 of 8
0

If you post code, please use the ‘Insert Code’ button. Please and thank you!

PLEASE READ BEFORE POSTING! Read if you're new to the PowerShell forum! Programming & Development
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…

🌐
Reddit
reddit.com › r/powershell › powershell noob here, can someone tell me how to obtain which properties i can pull for "get-aduser"? thanks
r/PowerShell on Reddit: Powershell noob here, can someone tell me how to obtain which properties I can pull for "get-aduser"? Thanks
August 24, 2023 -

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.

🌐
Spiceworks
community.spiceworks.com › programming & development
Get only user OU from Active Directory Using Powershell/CLI - #8 by nicolaslang - Programming & Development - Spiceworks Community
February 15, 2017 - As I wrote before : #and if you want only the first uo, you can split $uo and take the first index $uo.split(',')[0] So … write-host "$($user.Name) = $($uo.split(',')[0])"
🌐
Spiceworks
community.spiceworks.com › programming & development
How to get a users OU and store it as a variable to move other users to that OU - Programming & Development - Spiceworks Community
July 31, 2019 - I am using powershell to complete the below task. Long story short I have a Provisioned Users OU in AD where automation (FIM) places users when they are created. I have to manually go into the OU and move the users base…
🌐
Spiceworks
community.spiceworks.com › programming & development
Get only user OU from Active Directory Using Powershell/CLI - #6 by nicolaslang - Programming & Development - Spiceworks Community
February 15, 2017 - Woops, my bad. I copied a test line instead of the working one 😃 $user = get-aduser nicolas1847 $uo = $user.distinguishedname.substring($user.distinguishedname.indexof(",") + 1,$user.distinguishedname.Length - $user.distinguishedname.indexof(",") - 1)
🌐
Reddit
reddit.com › r/sysadminblogs › get-aduser syntax and example usage
r/SysAdminBlogs on Reddit: Get-ADUser Syntax and Example Usage
April 11, 2022 - Hey there. Here's a deep dive walk through of using Get-ADUser to pull back various bits of user account information from Active Directory. Let me…
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › activedirectory › get-adobject
Get-ADObject (ActiveDirectory) | Microsoft Learn
Derived types, such as the following, are also accepted: ... Returns one or more Active Directory objects. The Get-ADObject cmdlet returns a default set of ADObject property values.
🌐
PowerShell Gallery
powershellgallery.com › packages
PowerShell Gallery | Packages matching Cmdlets:"Get-ADUser" Displaying results 1 to 2 of 2
Repackaging Active Directory Module so you can install and use AD Powershell Cmdlet without admin right · PoshBot module for a variety of commands
🌐
IT Pro Today
itprotoday.com › powershell › digging-deeper-into-get-aduser
ITPro Today, Network Computing, IoT World Today combine with TechTarget | TechTarget
If you’re seeking topic-specific coverage, TechTarget.com offers in-depth reporting and analysis on key areas such as networking, IT operations, data management, artificial intelligence, and cybersecurity. Our extensive coverage ensures that you stay informed about the latest trends and business strategies shaping the IT industry.
🌐
LWS
lws.fr
Meilleur Hébergeur site web Français - Nom de domaine - Serveur VPS - LWS
Hébergeur de site Web avec nom de domaine, serveur dédié Linux et Windows, serveur VPS, stockage en ligne, sauvegardes et boutiques eCommerce.