Get mail from AD and replace it with ManagedBy

RASH MAAR 421 Reputation points
2021-01-20T18:10:51.147+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.

In this way it does work for me, But only if I ask about one server:

$11Server = Get-ADComputer -Filter {Name -eq ‘EXchangeServer’} -Properties ManagedBy | Select-Object -Property Name, @{label=’ManagedBy’;expression={$_.ManagedBy -replace ‘^CN=|,.*$’}}
$22Owner = $11Server.ManagedBy
$33mail = Get-ADUser -Filter {Name -eq $22Owner} -Properties mail | Select-Object mail
$11Server.ManagedBy = $33mail.mail
$11Server

Name ManagedBy
EXchangeServer Stevo.Polyi@Company portal .com

I would appreciate your help Thanks

Windows Server
Windows Server
A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.
12,176 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,381 questions
0 comments No comments
{count} votes

Accepted answer
  1. Rich Matheisen 45,091 Reputation points
    2021-01-20T19:36:25.087+00:00

    Here's the answer I gave you in your earlier question on the same subject: get-mail-from-ad-and-replace-with-name.html

    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  
    
    0 comments No comments

0 additional answers

Sort by: Most helpful