Get mail from AD and replace with name

RASH MAAR 421 Reputation points
2021-01-19T20:34:12.633+00:00

Hi team,
My goal is to create a CSV file with two data, the name of all the servers from Active Directory and the email of its owner.
In the first step I am asked about all the servers and who owns them:

$Servers = Get-ADComputer -Filter * -SearchBase 'OU=Servers,OU=CONTOSO Computers,DC=contoso,DC=lan' -Properties ManagedBy | Select-Object -Property Name, @{label='ManagedBy';expression={$_.ManagedBy -replace '^CN=|,.*$'}}

And now I have the names of the servers and the names of their owners in such mode:
Name ManagedBy
Server1 Stevo Polyi
Server2 Rich Turner
Server3 Kirk Baltz

Now I need to ask AD about the email of each of the names in ManagedBy and replace the name with the email, and here's the part I need help with. I tried all sorts of ways to query AD with the names in $Server.ManagedBy without success.
I would appreciate your help Thanks

Windows for business Windows Server User experience PowerShell
Windows for business Windows Server User experience Other
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Rich Matheisen 47,901 Reputation points
    2021-01-19T20:59:03.49+00:00

    See if this works for you:

    Get-ADComputer -Filter -SearchBase 'OU=Servers,OU=CONTOSO Computers,DC=contoso,DC=lan' -Properties Name, ManagedBy | 
        ForEach-Object{
            [PSCustomObject]@{
                Name = $_.Name
                ManagedBy = (Get-ADUser $_.ManagedBy | Select -Expand mail)
            }
        } Export-CSV c:\junk\X.csv -NoTypeInformation
    

    You may need to use Get-ADObject instead of Get-ADUser if the ManagedBy property contains the DN of an object other than a user.

    1 person found this answer helpful.

  2. Andreas Baumgarten 123.4K Reputation points MVP Volunteer Moderator
    2021-01-19T20:57:13.437+00:00

    The ManagedBy attribute returns a CN?

    If so, maybe this will help (not tested):

    Get-ADUser -LDAPFilter '(cn=<CN of Managed By User>' -Properties EmailAddress | Select EmailAddress 
    

    (If the reply was helpful please don't forget to upvote and/or accept as answer, thank you)

    Regards
    Andreas Baumgarten


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.