I was given another task today to filter out some users in a certain fashion. A coworker asked me to get a few properties and one of the OUs certain users were residing in. Our structure is as follows OU1,OU2,OU3,user accounts. I was asked with the distinguished name to get the OU2 name and if the user object wasn’t residing in the same OU structure as provided, then to filter it out. I came up with the following code to query the results.
Get-ADUser -Filter * -SearchBase "OU=<OU1>,OU=<OU2>,OU=<OU3>,DC=<DC1>,DC=<DC2>,DC=<DC3>,DC=<DC4>" -Properties Name, personalTitle, telephoneNumber, MobilePhone, EmailAddress | Select-Object -property Name, personalTitle, telephoneNumber, MobilePhone, EmailAddress, @{label='DistinguishedName';expression={($_.DistinguishedName -replace'(.*.-?OU=Users,OU=)|(,OU.*)') }} | Where-Object {($_.DistinguishedName -notlike '*CN=*')}
The first part grabbed the users I wanted where the second line did the initial filter to retrieve just the second OU name with the regex portion stripping away most of the junk I didn’t need. The third line then removed any objects not following the same OU structure.