2

What's the easiest way to get the OU containing an LDAP object in PowerShell?

I'm working on a script to manage some groups that I've made "dynamic" with a script, and I can get the full distinguished name with the below:

$PseudoDynamicGroupDN = (Get-ADGroup -Filter {Name -like $PseudoDynamicGroup}).DistinguishedName

It returns something like:

CN=MyPseudoDynamicGroup,OU=Users,OU=BusinessUnit,OU=Site,OU=Company,DC=domain,DC=forest,DC=tld

And I'm looking to discard the CN=MyPseudoDynamicGroup, bit so I end up with:

OU=Users,OU=BusinessUnit,OU=Site,OU=Company,DC=domain,DC=forest,DC=tld

How do I do this as easily as possible? I tried using the Split operator, but this returns an array, and strips out the commas, forcing me to add them back in. I suspect there's a better way.

  • Note: I self-answered, but am also interested in other solutions, so I'm going to leave it unaccepted for a while to give others a chance to provide a better answer. – HopelessN00b Jul 18 '17 at 14:05
2

The easiest way I've found so far is to use the .NET framework IndexOf method to get the index of the first instance of the comma character, and feed that to the .NET framework Substring method. I used the code below, which puts the desired string into a variable named PseudoDynamicGroupOU.

$PseudoDynamicGroupDN = (Get-ADGroup -Filter {Name -like $PseudoDynamicGroup}).DistinguishedName;
$PseudoDynamicGroupDNPosition = $PseudoDynamicGroupDN.IndexOf(",");
$PseudoDynamicGroupOU = $PseudoDynamicGroupDN.Substring($PseudoDynamicGroupDNPosition+1);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.