Stripping sections of an OU out to populate AD fields

Hi I am wanting to add a section to a script to use a certain segment of the users OU to populate fields in AD.

For example I know I can do Get-aduser $username -property distinguishedName to get the OU. I then want to know how I can strip out the below section for example:


Hope it makes sense


try below

$userObj = Get-aduser -Identity user1 

# grab the first OU, learnt this from Olaf in this forum :) 
$OU = ($userObj.DistinguishedName -split ',')[1]

#remove 'OU=' 
$OU -replace 'OU=',''

search the forum, should be a few more examples

This looks good but as our OU’s aren’t always the same length I need to work from the other end is that possible?

Or can I retrieve the OU to only a certain length to normalize it?

i assume you want the OU where the user is sitting in. don’t think the length matters.

# distinguished property in ad example
$DistinguishedName = 'CN=mawazo,OU=Location with very long name,OU=test users,OU=all users,DC=potato,DC=com'

# change string to array by splitting it using comma
$array =
$DistinguishedName -split ','

#you get this 

OU=Location with very long name
OU=test users 
OU=all users

# grab the first ou which is second from the list

#you get this
OU=Location with very long name

# to get the last ou

anyway as always the people here are helpful so someone will jump in to assist.

It might help to understand your goal a bit better.

The DN of just an OU looks like OU=AzureUsers,DC=contoso,DC=com
The DN of a user looks like CN=Bugs Bunny,OU=AzureUsers,DC=constoso,DC=com

To confirm, based on your opening post, you are just concerned with DNs of users. Correct?

And it sounds like you want everything between CN=Bugs Bunny and DC=constoso,DC=com So just the OUs.

If that is the case, then you just need to strip off the first part CN=Bugs Bunny and the last part DC=constoso,DC=com. If this is your goal, then the fact that OU=something,OU=something etc may vary shouldn’t matter.

The next question would be, if the above is correct, then how did you want the data and where did you want to put it in AD?

example options
option 1 = OU=something,OU=something,OU=something

options 2 = OU=something

After looking at this with fresh eyes this morning I realized I could use @mawazo solution but use negative values inside the to work backwards in the OU’s which was the only issue with the inital response.

Thank you @mawazo & @Matt for your replies.