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:
[email protected]
[email protected]
[email protected]
After I run the code, this is the output:
samAccountName UserPrincipalName DistinguishedName
aj [email protected] CN=Alex Jones, OU=users, OU=finance, OU=company, DC=company, DC=com
bp [email protected] CN=Bill Poppins, OU=users, OU=tech, OU=it, OU=company, DC=company, DC=com
ch [email protected] 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 [email protected] finance CN=Alex Jones, OU=users, OU=finance, OU=company, DC=company, DC=com
bp [email protected] tech CN=Bill Poppins, OU=users, OU=tech, OU=it, OU=company, DC=company, DC=com
ch [email protected] company CN=Cal Henry, OU=users, OU=company, DC=company, DC=com