Export-CSV differents parameters

Hello everyone,
I’m a newbee on powershell, i use the product for years, but since 3 months I have started to create scripts for my work… It’s hard because i don’t have the “basics”, but i enjoy Powershell.

Currently we need metrics for a new service, and I am working on a script which counts all the mails sent to different recipients on the day past.

I get the good values, and now i would like to export it on CSV format.

$Datecount = (Get-Date).AddDays(-1).ToString(“MM/dd/yyyy”)
$MailboxSRV = Get-MailboxServer | ? {$.name -match “EXCHANGE[1]0[12]”} | Sort-Object Name
$Recipients = Get-MailContact -OrganizationalUnit domain.prv/MSG/Contacts -Filter * | Where-Object {$
.Name -like “NEW-SERVICE*”}


foreach ($Contact in $Recipients)
$Count = foreach ($Server in $MailboxSRV)
(Get-MessageTrackingLog -Server $Server.Name -Recipients ($contact | select -ExpandProperty PrimarySmtpAddress | %{[string] $x = $_ ; $x}) -Start $Datecount" 00:00:00" -End $Datecount" 23:59:59" -ResultSize unlimited | ? {$_.Source -eq “SMTP”}).count
$Sum = $Count | Measure-Object -Sum | Select Sum
Write-Host $contact
Write-Host $Sum

And i get this result :


The result I want on CSV :


Thanks in advance!

Welcome to the forum. :wave:t4:

To use Write-Host is not a good idea. Instead you should create a proper object you can use for further steps then:

$Result =
foreach ($Contact in $Recipients) {
    $Count = 
    foreach ($Server in $MailboxSRV) {
        (Get-MessageTrackingLog -Server $Server.Name -Recipients ($contact | Select-Object -ExpandProperty PrimarySmtpAddress | ForEach-Object { [string] $x = $_ ; $x }) -Start $Datecount" 00:00:00" -End $Datecount" 23:59:59" -ResultSize unlimited | Where-Object { $_.Source -eq 'SMTP' }).count
    $Sum = $Count | Measure-Object -Sum | Select-Object Sum
        Contact = $Contact
        Sum     = $Sum.Sum -as [INT]

This should give you the ouput you expect. You can pipe this to Export-Csv for example. :wink:

Hi Olaf,
I tried your solution and it’s perfect!

Thanks a lot!