I have a powershell script that pulls emails using EWS managed API, reads their subject, from address, to address, and internetmessageheaders. Within the email read loop it loads all this information into a datatable.
I need to grab all the above information for each message and populate an array or datatable based on the from address. Then I’ll check for relay information and send the whole list based on from address to a target address.
I can’t seem to wrap my head around how to build the from address lists. I’ve tried turning the datatable data into a hashtable and then using a sort|get-unique to get a list of the unique from addresses but have not been able to use this information to correctly build the from address array. I’ve tried looping through using a select-string $_ -allmatches but haven’t gotten anywhere.
Here is part of my code, It creates the datatable and populates it using information from each email.
$msgTable = New-Object system.Data.DataTable “Messages”
$col1 = New-Object system.Data.DataColumn Subject,([string])
$col2 = New-Object system.Data.DataColumn From,([string])
$col3 = New-Object system.Data.DataColumn To,([string])
$col4 = New-Object system.Data.DataColumn Relay,([string])
$msgTable.columns.add($col1)
$msgTable.columns.add($col2)
$msgTable.columns.add($col3)
$msgTable.columns.add($col4)
$frItemResult = $PublicFolder.FindItems($sfCollection,$view)
# Loop through view results and mark read
$frItemResult | ForEach-object{
if($_.HasAttachments ) {
$_.Load()
"Report Subject: $($_.Subject)"
# Loop through attachments, extract info
$_.Attachments | ForEach-object {
if($_.Name -notmatch "ATT00001"){
$_.Load($attPropset)
$row = $msgTable.NewRow();$row.Subject = $($_.item.Subject); $row.From = ($_.item.From.address); $row.To = $($_.item.ToRecipients.address); $row.Relay = "$($_.Item.InternetMessageHeaders | Where-Object {$_.name -like "*received*"})";$msgTable.Rows.Add($row)
Here is what $msgTable looks like after data is populated.
Subject From To Relay
------- ---- -- -----
Message1 user1@company.com recipient1@yahoo.com Received-SPF=pass (domain of ...
Message2 user2@company.com recipient2@comcast.net Received=from imta27.mailguys...
Message2 user2@company.com recipient3@yahoo.com Received-SPF=pass (domain of ...
Message3 user3@company.com recipient4@sbcglobal.net Received-SPF=pass (domain of ...
I need to be able to grep out all the information for user2@company.com to another variable and do the same for any number of other repeating or non-repeating from addresses.
I’ll then take each of the from address variables and send it to the target recipient.
Any help is greatly appreciated.
Try using Group-Object, you can then run a foreach loop against each grouping: