0

I created this code to search for a group of users using a csv of emails:

$UserList = Get-Content C:\User\useremails.csv

foreach ($user in $UserList) {
    Get-ADUser -Filter {Emailaddress -eq $user}
    Get-ADUser -Filter {EmailAddress -eq $user} -Properties name | 
    Select samAccountName, UserPrincipalName, DistinguishedName | 
    Export-Csv C:\User\accounts.csv -Append -NoTypeInformation
}

It works, however, there's a lot of noise in the DistinguishedName column of the CSV. Is there a way to parse that column to only get a specific OU or can this be done before exporting the CSV?

Here is an example of what I mean:

I have useremails.csv:

alex.jones@mail.com
bill.poppin@mail.com
cal.henry@mail.com

After I run the code, this is the output:

samAccountName  UserPrincipalName   DistinguishedName            
aj              aj@mail.com         CN=Alex Jones, OU=users, OU=finance, OU=company, DC=company, DC=com
bp              bp@mail.com         CN=Bill Poppins, OU=users, OU=tech, OU=it, OU=company, DC=company, DC=com
ch              ch@mail.com         CN=Cal Henry, OU=users, OU=company, DC=company, DC=com  

If a user has an OU that shows a department, then thats the only OU I want. If a user only has users and the company name in OU then I only want the company name. But keeping the DistinguishedName column.

So this would be my desired output:

samAccountName  UserPrincipalName   OU         DistinguishedName                                                                                                               
aj              aj@mail.com         finance    CN=Alex Jones, OU=users, OU=finance, OU=company, DC=company, DC=com   
bp              bp@mail.com         tech       CN=Bill Poppins, OU=users, OU=tech, OU=it, OU=company, DC=company, DC=com
ch              ch@mail.com         company    CN=Cal Henry, OU=users, OU=company, DC=company, DC=com 
noobCoder
  • 89
  • 7

0 Answers0