0

I have a list of Active Directory group name in the form

cn=GROUPA,ou=Dept1,ou=Departmental Groups,ou=GROUPS1,dc=test,dc=server,dc=com

and I was wondering if there was a way to use the -replace function to remove all of the "ou=" and "dc=" sections. I know I could just use

-replace "ou=Dept1",""

but I want to know if there is a way I could replace "ou=Dept1" without knowing the Dept1 part, since not all of the group names include Dept1, but instead use other names. I was thinking maybe some way of using select-string with a -notlike, but I have not found a way yet. Thank you.

3 Answers 3

1

To remove all ou= and dc=

-replace 'dc=.+?,|dc=.+$|ou=.+?,',''

It will leave you with cn=GROUPA,. If you actually just want the cn part you can do:

-match '(cn=.+?),' | Out-Null
$matches[1]

In the second part of your question you can replace the ou= parts without knowing the name like this:

-replace 'ou=.+?', 'ou=test,'
Sign up to request clarification or add additional context in comments.

4 Comments

Am I reading the question wrong? It seems he wants to only keep the container part, so why are you removing it? ^^
That's what I interpreted ... a way to ... remove all of the "ou=" and "dc=" sections to mean @Graimer. The question as worded is a bit confusing TBH.
You're saying the same as me, but your answer is different. Your code is removing the CONTAINER(cn), not the domain comp.(dc) as it should.
oh LOL I see, I misread dc to be cn, Thx @Graimer, i'll fix it.
1

Yes, just use replace...

$myOUString.Replace(",ou",",dc")

Would replace each ,cn with ,dn and would also make sure that if there were a group that contained ou for some other reason you are OK, for eaxample Thousands would not become thdcsands.

$myOuString -Replace ",ou",",dc" should also work.

Eitherway, you should not need wildcards in your example, because you do not want to replace ou=ForgottenUsers with dc=

Comments

1

Coming at it from the other direction:

-replace '.+?(dc=.+)','$1'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.