How to get info in csv combine with result from PowerShell cmd?

SAM2009 used Ask the Experts™
Hi, I need help to code this in PowerShell:

$Users = Import-Csv "C:\temp\ExchangeMailboxes.csv"

ExchangeMailboxes.csv contains these info: SamAccountName,Mail

How can I get the mail info in ExchangeMailboxes.csv and the result of this cmd:

$Users | where {$_.domainFQDN -eq "mydomain"} | % {Get-ADUser -Identity $_.SamAccountName -Properties admindescription} | Select Name,SamAccountName,AdminDescription,Enabled

How can add mail info in the below cmd. So at the end I should get: Mail,Name,SamAccountName,AdminDescription,Enabled

Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2018
Distinguished Expert 2018
In general, you select one of the sources to merge and put it into a hash table, with the joining column as key.
Then you retrieve the other source and merge from the hashtable using a "calculated property".
It's not quite clear, though, where the second "$Users" is coming from (the one you use to retrieve the AD user from; it has a column "domainFQDN" that's not in your description of ExchangeMailboxes.csv.
So something like this (note: this will not work as it is, because $Users is not set here, due to the missing information I indicated above):
$lookup = @{}
Import-Csv "C:\temp\ExchangeMailboxes.csv" | ForEach-Object {$lookup[$_.SamAccountName] = $_}
$Users |
	Where-Object {$_.domainFQDN -eq "mydomain"} |
	ForEach-Object {
		Get-ADUser -Identity $_.SamAccountName -Properties admindescription |
			Select-Object @{n='Mail'; e={$lookup[$_.SamAccountName].Mail}}, Name, SamAccountName, AdminDescription, Enabled
	} | Export-Csv -NoTypeInformation -Path C:\Temp\merged.csv

Open in new window


Could you please explain me how I should read this:

ForEach-Object {$lookup[$_.SamAccountName] = $_
Most Valuable Expert 2018
Distinguished Expert 2018

$lookup is a hash table. The ForEach-Object takes each row of ExchangeMailboxes.csv, and adds it to the hash table, using the SamAccountName as key.
It's the fastest way to join the tables based on the common property SamAccountName.


Thanks a lot. That works fine!

Just a little correction. This need to be added: $Users = Import-Csv "C:\temp\ExchangeMailboxes.csv"

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial