[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$egurkhaPath=(Get-Item Env:EGURKHA_INSTALL_DIR).value.ToString()
$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
$egEncryPath=$scriptPath+"\EGFileEncryption.psm1"
$egDatnKy=$scriptPath+"\GetDatnKeyFiles.psm1"
Import-Module $egEncryPath,$egDatnKy
clear

$testargs=$args
#<#
$userName=$testargs[0]
$Password=Eg-O365Dcr -EncStr $testargs[1]
$proxyUsr=$testargs[2]
$proxyPass=Eg-O365Dcr -EncStr $testargs[3]
$rptTopNDD=[int]$testargs[4]
$otherdetails=$testargs[5]
$details=$otherdetails.split("#")
$toHideAdminTrfic=$details[0]
$reportingname='EXO/'+$details[1]
$proxyserverip=($details[2]).ToString().trim()
$ExcludeMails=$details[3]
$rptNamFrMT=$details[1]
#>

if($proxyUsr.toString().toLower().Trim() -eq 'none') { $proxyUsr=$proxyUsr.toString().toLower().Trim() }
if($proxyPass.toString().toLower().Trim() -eq 'none') { $proxyPass=$proxyPass.toString().toLower().Trim() }
if($proxyserverip.toString().toLower().Trim().Contains('none')) { $proxyserverip=$proxyserverip.toString().toLower().Trim() }
$proxyserver='http://'+$proxyserverip

$filepath=$egurkhaPath+'/agent/'+$reportingname+'/'
try{
    $filereaded=Get-ChildItem -Path $filepath |Where-Object {$_.Name -like 'msgs*.dat'}| Sort-Object LastWriteTime -Descending | Select-Object -First 2 
    if($filereaded.Length -eq 2){
        if($filereaded[0].Length -lt 100 -and $filereaded[1].Length -ge 100){
            $fileName=([String]$filereaded[0].Name).Trim()
            Remove-Item $filepath$fileName
        }
    }  
    $readfiles1=Eg-ReadFile -ComntRptPath $reportingname -FileName "msgs" -keyFileName "kmsgs" -EgPath $egurkhaPath
    $datafile1=$readfiles1[1] -replace (".csv",".dat") 
    $csvfile1=Unprotect-File $datafile1 -Algorithm AES -KeyAsPlainText $readfiles1[0]
    $MessageTracetemp= import-csv $csvfile1    
    Remove-Item $csvfile1
    Eg-DeleteFiles -FilePath $readfiles1[2] -Pattern 'msgs' -InputFile $readfiles1[3]
    Eg-DeleteFiles -FilePath $readfiles1[2] -Pattern 'kmsgs' -InputFile $readfiles1[4]
    Write-Host 'ReadFile:'$readfiles1[3]   
}
catch [System.Management.Automation.RuntimeException] {
    Write-Error -Message "File not found. The $reportingname location does not contain msgs files."
}
catch{
    $errmsg=$_.Exception.Message
    $errstack=$_.Exception.StackTrace
    Write-Error -Message $errmsg
}

if ( Test-Path $filepath -PathType Container ) {
    
    if($rptNamFrMT -match '_exd'){
        $alldomainnames=@()
	    $dhash=Eg-O635Domains -username $userName -password $Password -rptNam $rptNamFrMT -proxyserverip $proxyserverip -proxyUsr $proxyUsr -proxyPass $proxyPass
    	foreach($h in $dhash.Keys){
	        if($dhash[$h] -match $rptNamFrMT){
		        $alldomainnames+=$h        
	        }
	    }
    }else{
        $alldomainnames=Eg-GetDomain -userName $username -Password $Password -proxyUsr $proxyUsr -proxyPass $proxyPass -proxyserver $proxyserver       
    }
	$remvedmails=New-Object System.Collections.ArrayList
    if($toHideAdminTrfic -eq $true){           
        [void]$remvedmails.Add($username)   
    }
    try{
        if($ExcludeMails.Contains(',')){        
            $ExcludeMails=$ExcludeMails.Split(',')      
        }
    }catch{  $ExcludeMails=" "}

    foreach( $ExcludeMail in  $ExcludeMails){        
       [void] $remvedmails.Add($ExcludeMail)
    }

    #each domain process
    foreach($domainname in $alldomainnames){  
        $tmpdomainname = "@"+$domainname 
        if($MessageTracetemp.SenderAddress -match $tmpdomainname -or $MessageTracetemp.RecipientAddress -match $tmpdomainname){
            $domainname=$domainname.ToString().ToLower() 
            Write-host 'gettingmeasuresofSpecificDomains#' $domainname
            $unqSendersHT = New-Object System.Collections.Hashtable
            $unqRecepientsHT = New-Object System.Collections.Hashtable
            $FmIPHT = New-Object System.Collections.Hashtable       
            $Pending=0
            $None=0
            $Failed=0
            $Delivered=0
            $Expanded=0
            $Resolved=0
            $GettingStatus=0
            $Quarantined=0
            $Unknown=0
            $FilteredAsSpam=0
            $interMailSent=0
            $sizeinterMailSent=0
            $exterMailSent=0
            $sizeexterMailSent=0
            $interMailRevd=0
            $sizeinterMailRevd=0
            $exterMailRevd=0
            $sizeexterMailRevd=0
            $MailInboundTraffic = @{} 
            $MailOutboundTraffic = @{} 
            $MailOutTraffic=@{}
            $mailOutTrfcExsent=@{}
            $MailInTrafficSent=@{}
            $MailInTrafficRevd=@{}
            $MailInboundDomain=@{}
            $MailOutboundDomain=@{}
            $delstatuscnt=0
  
            #for each domain the data will be processed in this loop
            foreach($Message in $MessageTracetemp){ 
                if($Message.SenderAddress -match $remvedmails -and $Message.RecipientAddress -match $remvedmails -and $remvedmails -match " " -and $remvedmails -match $null){}
                else{        
                    $sendersDomain = "" 
                    $RecipientDomain=""
                    try{$sendersDomain=(($Message.SenderAddress).split('@')[1]).ToString().ToLower()}catch{$sendersDomain=""}
                    try{$RecipientDomain=(($Message.RecipientAddress).split('@')[1]).ToString().ToLower()}catch{$RecipientDomain=""}                
                    if(($sendersDomain-ne "" -and $domainname -eq $sendersDomain) -or ($RecipientDomain -ne "" -and $domainname -eq $RecipientDomain)) {
                        try{$unqSendersHT.Add($Message.SenderAddress,$Message.SenderAddress)}catch{} 
                        try{$unqRecepientsHT.Add($Message.RecipientAddress,$Message.RecipientAddress)}catch{}
                        try{$FmIPHT.Add($Message.FromIP,$Message.FromIP)}catch{}
                               
                        ## message delivery status
                        $Status = $Message.Status
                        if($Status -eq 'Delivered' -and $Status -ne $null){$Delivered++} 
                        elseif($Status -eq 'Expanded' -and $Status -ne $null){$Expanded++}
                        elseif($Status -eq 'Resolved' -and $Status -ne $null){$Resolved++}
                        elseif($Status -eq 'Pending' -and $Status -ne $null){$Pending++}   
                        elseif($Status -eq 'Failed' -and $Status -ne $null){$Failed++}
                        elseif($Status -eq 'GettingStatus' -and $Status -ne $null){$GettingStatus++}
                        elseif($Status -eq 'Quarantined' -and $Status -ne $null){$Quarantined++}
                        elseif($Status -eq 'Unknown' -and $Status -ne $null){$Unknown++}
                        elseif($Status -eq 'None' -and $Status -ne $null){$None++} 
                        elseif($Status -eq 'FilteredAsSpam' -and $Status -ne $null){$FilteredAsSpam++}

                        #Read each message tracking entry and add it to a hash table
                        $MessageSenderAddress=$Message.SenderAddress+'#'+$Message.FromIP
	                    if ($Message.SenderAddress -ne $null -and $domainname.Contains($sendersDomain)) {
		                    if ($MailOutboundTraffic.ContainsKey($MessageSenderAddress)) { 
		                        $MailOutboundTraffic[$MessageSenderAddress]['Outbound']++ 
		                        $MailOutboundTraffic[$MessageSenderAddress]['OutboundSize'] += [int]$Message.Size
    	                    }
                            else{
                                $MailOutboundTraffic[$MessageSenderAddress] = @{}
	                            $MailOutboundTraffic[$MessageSenderAddress]['Outbound']= 1
	                            $MailOutboundTraffic[$MessageSenderAddress]['Inbound']=0
	                            $MailOutboundTraffic[$MessageSenderAddress]['InboundSize']= 0
	                            $MailOutboundTraffic[$MessageSenderAddress]['OutboundSize']= [int]$Message.Size
                            }
	                    }
	                    if ($Message.RecipientAddress -ne $null -and $domainname.Contains($RecipientDomain)) { 
		                    if ($MailInboundTraffic.ContainsKey($MessageSenderAddress)){ 
			                    $MailInboundTraffic[$MessageSenderAddress]['Outbound']++ 
			                    $MailInboundTraffic[$MessageSenderAddress]['OutboundSize'] += [int]$Message.Size
		                    }
                            else{
                                $MailInboundTraffic[$MessageSenderAddress] = @{}
	                            $MailInboundTraffic[$MessageSenderAddress]['Outbound']= 1
	                            $MailInboundTraffic[$MessageSenderAddress]['Inbound']=0
	                            $MailInboundTraffic[$MessageSenderAddress]['InboundSize']= 0
	                            $MailInboundTraffic[$MessageSenderAddress]['OutboundSize']= [int]$Message.Size
                            }     
	                    }
       
		                if( $domainname.Contains($sendersDomain) -and $domainname.Contains($RecipientDomain)){
			                $interMailSent++
			                $sizeinterMailSent=$sizeinterMailSent+$Message.Size

		                    ##internal mail sent to our domain from our domain // sending means outbound
            	    
		                    if($MailInTrafficSent.ContainsKey($MessageSenderAddress)){
			                    $MailInTrafficSent[$MessageSenderAddress]['Outbound']++
			                    $MailInTrafficSent[$MessageSenderAddress]['OutboundSize'] +=[int]$Message.Size
		                    }
		                    else{
			                    $MailInTrafficSent[$MessageSenderAddress]=@{}
			                    $MailInTrafficSent[$MessageSenderAddress]['Inbound']=0
			                    $MailInTrafficSent[$MessageSenderAddress]['InboundSize']=0
			                    $MailInTrafficSent[$MessageSenderAddress]['Outbound']=1
			                    $MailInTrafficSent[$MessageSenderAddress]['OutboundSize']=[int]$Message.Size
		                    }   
		    
		                    ## internal mail reciving an mail from our domain //reciving inbound
		                    if($Message.Status -eq 'Delivered'){         
			                    $interMailRevd++
			                    $sizeinterMailRevd=$sizeinterMailRevd+$Message.Size
		                        if($MailInTrafficRevd.ContainsKey($Message.RecipientAddress)){
			                        $MailInTrafficRevd[$Message.RecipientAddress]['Inbound']++
			                        $MailInTrafficRevd[$Message.RecipientAddress]['InboundSize'] +=[int]$Message.Size
		                        }
		                        else{
			                        $MailInTrafficRevd[$Message.RecipientAddress]=@{}
			                        $MailInTrafficRevd[$Message.RecipientAddress]['Inbound']=1
			                        $MailInTrafficRevd[$Message.RecipientAddress]['InboundSize']=[int]$Message.Size
			                        $MailInTrafficRevd[$Message.RecipientAddress]['Outbound']=0
			                        $MailInTrafficRevd[$Message.RecipientAddress]['OutboundSize']=0
		                        }
		                    }           
		                }
		                elseif( $domainname.Contains($sendersDomain) -and !($domainname.Contains($RecipientDomain))){
			                $exterMailRevd++                   #external mail recived an mail from our domain  ## measure ui name is Externalemails sent
			                $sizeexterMailRevd=$sizeexterMailRevd+$Message.Size

		                    if($mailOutTrfcExsent.ContainsKey($MessageSenderAddress)){
			                    $mailOutTrfcExsent[$MessageSenderAddress]['Outbound']++
			                    $mailOutTrfcExsent[$MessageSenderAddress]['OutboundSize'] +=[int]$Message.Size
		                    }
		                    else{
			                    $mailOutTrfcExsent[$MessageSenderAddress]=@{}
			                    $mailOutTrfcExsent[$MessageSenderAddress]['Inbound']=0
			                    $mailOutTrfcExsent[$MessageSenderAddress]['InboundSize']=0
			                    $mailOutTrfcExsent[$MessageSenderAddress]['Outbound']=1
			                    $mailOutTrfcExsent[$MessageSenderAddress]['OutboundSize']=[int]$Message.Size
		                    }
		                }
	                    elseif(!($domainname.Contains($sendersDomain)) -and $domainname.Contains($RecipientDomain)){
                            $exterMailSent++           #External mail sent an mail to our domain  outbound
                            $sizeexterMailSent=$sizeexterMailSent+$Message.Size
                            if($MailOutTraffic.ContainsKey($MessageSenderAddress)){
                                $MailOutTraffic[$MessageSenderAddress]['Outbound']++
                                $MailOutTraffic[$MessageSenderAddress]['OutboundSize'] +=[int]$Message.Size
                            }
                            else{
                                $MailOutTraffic[$MessageSenderAddress]=@{}
                                $MailOutTraffic[$MessageSenderAddress]['Inbound']=0
                                $MailOutTraffic[$MessageSenderAddress]['InboundSize']=0
                                $MailOutTraffic[$MessageSenderAddress]['Outbound']=1
                                $MailOutTraffic[$MessageSenderAddress]['OutboundSize']=[int]$Message.Size
                            }
                        }
       
		                ###Message Status DD
         
                        if($delstatuscnt -lt $rptTopNDD -and ($Message.Status -eq 'None' -or $Message.Status -eq 'Failed' -or $Message.Status -eq 'Pending' -or $Message.Status -eq 'Unknown' -or $Message.Status -eq 'Quarantined') ){
		                    $size=(($Message.Size)/1024).tostring("#.##").replace(',','.')
	                        Write-Host '#delstatusdd'$Message.Status $Message.Received '~!~'$Message.SenderAddress '~!~' $Message.RecipientAddress '~!~' $Message.Subject '~!~' $size '~!~' $Message.FromIP                    		    
                            $delstatuscnt++;
                        }elseif($FilteredAsSpam -lt $rptTopNDD -and $Message.Status -eq 'FilteredAsSpam'){                    
		                    $size=(($Message.Size)/1024).tostring("#.##").replace(',','.')  
                            Write-Host "#delstatusdd Spam" $Message.Received'~!~'$Message.SenderAddress'~!~'$Message.RecipientAddress'~!~'$Message.Subject'~!~'$size '~!~'$Message.FromIP           
                        }
         
                       if($sendersDomain -ne "" -and $sendersDomain -ne $null -and !($domainname.Contains($sendersDomain))){
                            if($MailInboundDomain.ContainsKey($sendersDomain)){
			                    $MailInboundDomain[$sendersDomain]['Outbound']++
			                    $MailInboundDomain[$sendersDomain]['OutboundSize']+=[int]$Message.Size                   
                            }
                            else{
				                $MailInboundDomain[$sendersDomain]=@{}
			                    $MailInboundDomain[$sendersDomain]['Inbound']=0
			                    $MailInboundDomain[$sendersDomain]['InboundSize']=0
			                    $MailInboundDomain[$sendersDomain]['Outbound']=1
			                    $MailInboundDomain[$sendersDomain]['OutboundSize']=[int]$Message.Size
                            }
                       }
                       if($RecipientDomain -ne "" -and $RecipientDomain -ne $null -and !($domainname.Contains($RecipientDomain))){
                            if($MailOutboundDomain.ContainsKey($RecipientDomain)){
			                    $MailOutboundDomain[$RecipientDomain]['Inbound']++
			                    $MailOutboundDomain[$RecipientDomain]['InboundSize']+=[int]$Message.Size                   
                            }
                            else{
				                $MailOutboundDomain[$RecipientDomain]=@{}
			                    $MailOutboundDomain[$RecipientDomain]['Inbound']=1
			                    $MailOutboundDomain[$RecipientDomain]['InboundSize']=[int]$Message.Size
			                    $MailOutboundDomain[$RecipientDomain]['Outbound']=0
			                    $MailOutboundDomain[$RecipientDomain]['OutboundSize']=0
                            }
                        }                              
                    }            
                }        
            }

            write-host 'SenderAddress' $unqSendersHT.Keys.Count"#@!"
            write-host 'RecipientAddress' $unqRecepientsHT.Keys.Count"#@!"
            write-host 'FromIP' $FmIPHT.Keys.Count"#@!"

            ## message delivery status measures
	        Write-Host '#statusMeasure' $None' ~' $Failed' ~' $Pending' ~'  $Delivered '~' $Expanded '~' $Resolved  '~' $FilteredAsSpam '~' $GettingStatus '~' $Quarantined '~' $Unknown 	          

	        #Build a table to format the results 
	        $table = New-Object system.Data.DataTable "DetailedMessageStats" 
	        $col2 = New-Object system.Data.DataColumn Recipient,([string]) 
	        $table.columns.add($col2) 
	        $col3 = New-Object system.Data.DataColumn Inbound,([long]) 
	        $table.columns.add($col3) 
	        $col4 = New-Object system.Data.DataColumn Outbound,([long]) 
	        $table.columns.add($col4)
	        $col5 = New-Object system.Data.DataColumn InboundSize,([long]) 
	        $table.columns.add($col5) 
	        $col6 = New-Object system.Data.DataColumn OutboundSize,([long]) 
	        $table.columns.add($col6) 

	        $intable=New-Object system.Data.DataTable "DetailedMessageStats" #table for out emails
	        $incol2 = New-Object system.Data.DataColumn Recipient,([string]) 
	        $intable.columns.add($incol2) 
	        $incol3 = New-Object system.Data.DataColumn Inbound,([long]) 
	        $intable.columns.add($incol3) 
	        $incol4 = New-Object system.Data.DataColumn Outbound,([long]) 
	        $intable.columns.add($incol4) 
	        $incol5 = New-Object system.Data.DataColumn InboundSize,([long]) 
	        $intable.columns.add($incol5) 
	        $incol6 = New-Object system.Data.DataColumn OutboundSize,([long]) 
	        $intable.columns.add($incol6) 

	        $outtable=New-Object system.Data.DataTable "DetailedMessageStats" #table for out emails
	        $tcol2 = New-Object system.Data.DataColumn Recipient,([string]) 
	        $outtable.columns.add($tcol2) 
	        $tcol3 = New-Object system.Data.DataColumn Inbound,([long]) 
	        $outtable.columns.add($tcol3) 
	        $tcol4 = New-Object system.Data.DataColumn Outbound,([long]) 
	        $outtable.columns.add($tcol4) 
	        $tcol5 = New-Object system.Data.DataColumn InboundSize,([long]) 
	        $outtable.columns.add($tcol5) 
	        $tcol6 = New-Object system.Data.DataColumn OutboundSize,([long]) 
	        $outtable.columns.add($tcol6) 

	        $Inbunddomainstab=New-Object system.Data.DataTable "Detailed Sender Domains Stats" #table for out emails
	        $tcol1 = New-Object system.Data.DataColumn Recipient,([string]) 
	        $Inbunddomainstab.columns.add($tcol1) 
	        $tcol2 = New-Object system.Data.DataColumn Outbound,([long]) 
	        $Inbunddomainstab.columns.add($tcol2)  
	        $tcol3 = New-Object system.Data.DataColumn OutboundSize,([long]) 
	        $Inbunddomainstab.columns.add($tcol3) 

	        $Outbunddomainstab=New-Object system.Data.DataTable "Detailed Recipents Domains Stats" #table for out emails
	        $tcol1 = New-Object system.Data.DataColumn Recipient,([string]) 
	        $Outbunddomainstab.columns.add($tcol1) 
	        $tcol2 = New-Object system.Data.DataColumn Inbound,([long]) 
	        $Outbunddomainstab.columns.add($tcol2) 
	        $tcol3 = New-Object system.Data.DataColumn InboundSize,([long]) 
	        $Outbunddomainstab.columns.add($tcol3) 
 
	        #Transpose hashtable to datatable 
	        $TotalInboundSize=0 
	        $TotalOutboundSize=0
	        $TotalInboundItems=0
	        $TotalOutboundItems=0
    
  	        ForEach ($Recipient in $MailInboundTraffic.keys){ 
	            $RecipientName = $Recipient 
	            $row = $table.NewRow() 
		        $row.Recipient = $RecipientName 
		        $row.Inbound = $MailInboundTraffic[$RecipientName].Inbound 
		        $row.Outbound = $MailInboundTraffic[$RecipientName].Outbound 
		        $row.InboundSize = ($MailInboundTraffic[$RecipientName].InboundSize)/1024
		        $row.OutboundSize = ($MailInboundTraffic[$RecipientName].OutboundSize)/1024
		        $table.Rows.Add($row)     
		        $TotalInboundSize = $TotalInboundSize + $MailInboundTraffic[$RecipientName].OutboundSize
		        $TotalInboundItems = $TotalInboundItems + $MailInboundTraffic[$RecipientName].Outbound

	        } 
	        #Export data to CSV and Screen 
              
	        #"*******Top 10 Recipients by Inbound size*******" 
	        $InSize=$table  | sort OutboundSize -Descending | select -first $rptTopNDD #| ConvertTo-Csv -NoTypeInformation -Delimiter "," | % {$_ -replace '"',''}
	
   	        foreach($s in $InSize){
                $inbundsize=if($s.Item(3) -gt 0){ ($s.Item(3)).tostring("#.##").replace(',','.') } else { 0 }
                $outboundsize=if($s.Item(4) -gt 0){ ($s.Item(4)).tostring("#.##").replace(',','.') } else { 0 }
                $mailIPadress=($s.Item(0)).ToString().split('#')
	            Write-Host  'InboundSize ' $mailIPadress[0] ','$s.Item(1)','$s.Item(2)','$inbundsize','$outboundsize',' $mailIPadress[1]
	        }
            #"*******Top 10 Recipients by Inbound items*******" 
	        $InItems=$table | sort Outbound -Descending | select -first $rptTopNDD #| ConvertTo-Csv -NoTypeInformation -Delimiter "," | % {$_ -replace '"',''}
    
   	        foreach($s in $InItems){
                $inbundsize=if($s.Item(3) -gt 0){ ($s.Item(3)).tostring("#.##").replace(',','.') } else { 0 }
                $outboundsize=if($s.Item(4) -gt 0){ ($s.Item(4)).tostring("#.##").replace(',','.') } else { 0 }
                $mailIPadress=($s.Item(0)).ToString().split('#')
                Write-Host  'InboundItems ' $mailIPadress[0] ','$s.Item(1)','$s.Item(2)','$inbundsize','$outboundsize',' $mailIPadress[1]
	        }
   	        $table.Rows.Clear()  # clearing all rows of the outable 
    
   	        ForEach ($Recipient in $MailOutboundTraffic.keys){ 
	            $RecipientName = $Recipient 
	            $row = $table.NewRow() 
		        $row.Recipient = $RecipientName 
		        $row.Inbound = $MailOutboundTraffic[$RecipientName].Inbound 
		        $row.Outbound = $MailOutboundTraffic[$RecipientName].Outbound 
		        $row.InboundSize = ($MailOutboundTraffic[$RecipientName].InboundSize)/1024
		        $row.OutboundSize = ($MailOutboundTraffic[$RecipientName].OutboundSize)/1024
		        $table.Rows.Add($row)   
		        $TotalOutboundSize = $TotalOutboundSize + $MailOutboundTraffic[$RecipientName].OutboundSize
		        $TotalOutboundItems = $TotalOutboundItems + $MailOutboundTraffic[$RecipientName].Outbound
	        }
   	        #"*******Top 10 Senders by Outbound size*******" 
	        $outSize=$table | sort OutboundSize -Descending | select -first $rptTopNDD #| ConvertTo-Csv -NoTypeInformation -Delimiter "," | % {$_ -replace '"',''}
    
  	        foreach($s in $outSize){
                $inbundsize=if($s.Item(3) -gt 0){ ($s.Item(3)).tostring("#.##").replace(',','.') } else { 0 }
                $outboundsize=if($s.Item(4) -gt 0){ ($s.Item(4)).tostring("#.##").replace(',','.') } else { 0 }
                $mailIPadress=($s.Item(0)).ToString().split('#')
	            Write-Host  'OutboundSize ' $mailIPadress[0] ','$s.Item(1)','$s.Item(2)','$inbundsize','$outboundsize',' $mailIPadress[1]
	        } 
   	            #"*******Top 10 Senders by Outbound items*******" 
	            $outitems = $table | sort Outbound -Descending | select -first $rptTopNDD #| ConvertTo-Csv -NoTypeInformation -Delimiter "," | % {$_ -replace '"',''} 
    
	        foreach($s in $outitems){
                $inbundsize=if($s.Item(3) -gt 0){ ($s.Item(3)).tostring("#.##").replace(',','.') } else { 0 }
                $outboundsize=if($s.Item(4) -gt 0){ ($s.Item(4)).tostring("#.##").replace(',','.') } else { 0 }
                $mailIPadress=($s.Item(0)).ToString().split('#')
	            Write-Host  'OutboundItems ' $mailIPadress[0] ','$s.Item(1)','$s.Item(2)','$inbundsize','$outboundsize',' $mailIPadress[1]
	        }
   
	        #"*******Totals*******"
	        $TotalItems=$TotalInboundItems+$TotalOutboundItems
	        $TotalSize=$TotalInboundSize+$TotalOutboundSize 
            $TotalInboundSize=if([math]::round($TotalInboundSize /1Gb, 2) -gt 0){ ([math]::round($TotalInboundSize /1Gb, 2)).tostring("#.##").replace(',','.') } else { 0 }
            $TotalOutboundSize=if([math]::round($TotalOutboundSize /1Gb, 2) -gt 0){ ([math]::round($TotalOutboundSize /1Gb, 2)).tostring("#.##").replace(',','.') } else { 0 }
            $TotalSize=if([math]::round($TotalSize /1Gb, 2) -gt 0){ ([math]::round($TotalSize /1Gb, 2)).tostring("#.##").replace(',','.') } else { 0 }
	        write-host "Totals "$TotalInboundSize ~ $TotalOutboundSize ~ $TotalInboundItems ~ $TotalOutboundItems ~ $TotalItems ~ $TotalSize"#@!" 

	        #$table | sort Date,Recipient,Inbound,Outbound, InboundSize, OutboundSize -desc | Out-GridView -Title "Messages Sent By User"
	        $sizeinterMailSent=if([math]::round($sizeinterMailSent /1Gb, 2) -gt 0){ ([math]::round($sizeinterMailSent /1Gb, 2)).tostring("#.##").replace(',','.') } else { 0 }
	        $sizeinterMailRevd=if([math]::round($sizeinterMailRevd /1Gb, 2) -gt 0){ ([math]::round($sizeinterMailRevd /1Gb, 2)).tostring("#.##").replace(',','.') } else { 0 }
	        $sizeexterMailSent=if([math]::round($sizeexterMailSent /1Gb, 2) -gt 0){ ([math]::round($sizeexterMailSent /1Gb, 2)).tostring("#.##").replace(',','.') } else { 0 }
	        $sizeexterMailRevd=if([math]::round($sizeexterMailRevd /1Gb, 2) -gt 0){ ([math]::round($sizeexterMailRevd /1Gb, 2)).tostring("#.##").replace(',','.') } else { 0 }    
	        Write-Host  'emailsCountAndSize##' $interMailSent ~ $sizeinterMailSent  ~ $interMailRevd ~ $sizeinterMailRevd ~ $exterMailSent ~ $sizeexterMailSent ~ $exterMailRevd ~ $sizeexterMailRevd
   
            ForEach ($Recipient in $MailOutTraffic.keys) { 
	            $RecipientName = $Recipient 	     
		        $row = $outtable.NewRow() 
		        #$row.Date = $Date 
		        $row.Recipient = $RecipientName 
		        $row.Inbound = $MailOutTraffic[$RecipientName].Inbound 
		        $row.Outbound = $MailOutTraffic[$RecipientName].Outbound 
		        $row.InboundSize = ($MailOutTraffic[$RecipientName].InboundSize)/1024
		        $row.OutboundSize = ($MailOutTraffic[$RecipientName].OutboundSize)/1024
		        $outtable.Rows.Add($row)     
	        }
   	        # $exterMailRevd++           #external mail recived an mail from our domain inbound
	        # $exterMailSent++           #External mail sent an mail to our domain  outbound
	        #"*******Top 10 External Recipients by Outbound items*******" 
	        $Externalemailsent = $outtable | sort Outbound -Descending | select -first $rptTopNDD #| ConvertTo-Csv -NoTypeInformation -Delimiter "," | % {$_ -replace '"',''} 
    
   	        foreach($s in $Externalemailsent){
                $inbundsize=if($s.Item(3) -gt 0){ ($s.Item(3)).tostring("#.##").replace(',','.') } else { 0 }
                $outboundsize=if($s.Item(4) -gt 0){ ($s.Item(4)).tostring("#.##").replace(',','.') } else { 0 }
                $mailIPadress=($s.Item(0)).ToString().split('#')
	           Write-Host  'Externalemailsent ' $mailIPadress[0] ','$s.Item(1)','$s.Item(2)','$inbundsize','$outboundsize',' $mailIPadress[1]
	        }

            $outtable.Rows.Clear()  # clearing all rows of the outable 

   	        ForEach ($Recipient in $mailOutTrfcExsent.keys) { 
	            $RecipientName = $Recipient 	     
		        $row = $outtable.NewRow() 
		        #$row.Date = $Date 
		        $row.Recipient = $RecipientName 
		        $row.Inbound = $mailOutTrfcExsent[$RecipientName].Inbound 
		        $row.Outbound = $mailOutTrfcExsent[$RecipientName].Outbound
		        $row.InboundSize = ($mailOutTrfcExsent[$RecipientName].InboundSize)/1024
		        $row.OutboundSize = ($mailOutTrfcExsent[$RecipientName].OutboundSize)/1024
		        $outtable.Rows.Add($row)     
	        }
   	        #"*******Top 10 External Recipients by Inbound items*******" 
	        $Externalemailrecived = $outtable | sort Outbound -Descending | select -first $rptTopNDD #| ConvertTo-Csv -NoTypeInformation -Delimiter "," | % {$_ -replace '"',''} 
    
  	        foreach($s in $Externalemailrecived){
                $inbundsize=if($s.Item(3) -gt 0){ ($s.Item(3)).tostring("#.##").replace(',','.') } else { 0 }
                $outboundsize=if($s.Item(4) -gt 0){ ($s.Item(4)).tostring("#.##").replace(',','.') } else { 0 }
                $mailIPadress=($s.Item(0)).ToString().split('#')      
	          Write-Host  'Externalemailrecived' $mailIPadress[0] ','$s.Item(1)','$s.Item(2)','$inbundsize','$outboundsize',' $mailIPadress[1]
	        }
         
 	        ForEach ($Recipient in $MailInTrafficSent.keys){ 
	            $RecipientName = $Recipient 	     
		        $row = $intable.NewRow() 
		        $row.Recipient = $RecipientName 
		        $row.Inbound = $MailInTrafficSent[$RecipientName].Inbound 
		        $row.Outbound = $MailInTrafficSent[$RecipientName].Outbound 
		        $row.InboundSize = ($MailInTrafficSent[$RecipientName].InboundSize)/1024 
		        $row.OutboundSize = ($MailInTrafficSent[$RecipientName].OutboundSize)/1024
		        $intable.Rows.Add($row)     
	        }
  
	        #"*******Top 10 Internal Recipients by Outbound items*******" 
	        $Internalemailsent = $intable | sort Outbound -Descending | select -first $rptTopNDD #| ConvertTo-Csv -NoTypeInformation -Delimiter "," | % {$_ -replace '"',''}
    
 	        foreach($s in $Internalemailsent){
                $inbundsize=if($s.Item(3) -gt 0){ ($s.Item(3)).tostring("#.##").replace(',','.') } else { 0 }
                $outboundsize=if($s.Item(4) -gt 0){ ($s.Item(4)).tostring("#.##").replace(',','.') } else { 0 }
                $mailIPadress=($s.Item(0)).ToString().split('#')
	          Write-Host  'Internalemailsent ' $mailIPadress[0] ','$s.Item(1)','$s.Item(2)','$inbundsize','$outboundsize',' $mailIPadress[1]
	        }

            $intable.Rows.Clear()  # clearing all rows of the intable 

 	        ForEach ($Recipient in $MailInTrafficRevd.keys){ 
	            $RecipientName = $Recipient 	     
		        $row = $intable.NewRow() 
		        $row.Recipient = $RecipientName 
		        $row.Inbound = $MailInTrafficRevd[$RecipientName].Inbound 
		        $row.Outbound = $MailInTrafficRevd[$RecipientName].Outbound 
		        $row.InboundSize = ($MailInTrafficRevd[$RecipientName].InboundSize)/1024
		        $row.OutboundSize = ($MailInTrafficRevd[$RecipientName].OutboundSize)/1024
		        $intable.Rows.Add($row)     
	        }
	        #"*******Top 10 Internal Recipients by Inbound items*******" 
	        $Internalemailreceving = $intable | sort Inbound -Descending | select -first $rptTopNDD #| ConvertTo-Csv -NoTypeInformation -Delimiter "," | % {$_ -replace '"',''} 
    
 	        foreach($s in $Internalemailreceving){
                $inbundsize=if($s.Item(3) -gt 0){ ($s.Item(3)).tostring("#.##").replace(',','.') } else { 0 }
                $outboundsize=if($s.Item(4) -gt 0){ ($s.Item(4)).tostring("#.##").replace(',','.') } else { 0 }
                $mailIPadress=($s.Item(0)).ToString().split('#')
	          Write-Host  'Internalemailreceving ' $mailIPadress[0] ','$s.Item(1)','$s.Item(2)','$inbundsize','$outboundsize',' $mailIPadress[1]
	        }
              ## ADDING ROWS TO TABLE
            $sendercount=0
    
            ForEach ($Recipient in $MailInboundDomain.keys){ 
	            $RecipientName = $Recipient 
	            $sendercount++
		        $row = $Inbunddomainstab.NewRow() 
		        $row.Recipient = $RecipientName 
		        $row.Outbound = $MailInboundDomain[$RecipientName].Outbound 
		        $row.OutboundSize = ($MailInboundDomain[$RecipientName].OutboundSize)/1024
		        $Inbunddomainstab.Rows.Add($row)     
	        }
 	        #"*******Top 10 Sender Domains by Outbound items*******" 
	        $unquesendrdoms = $Inbunddomainstab | sort Outbound -Descending #| select -first 10 | ConvertTo-Csv -NoTypeInformation -Delimiter "," | % {$_ -replace '"',''}
            $uniqueRecipentDomainsCnt = 0
            foreach($s in $unquesendrdoms){
               $inbundsize=if($s.Item(2) -gt 0){ ($s.Item(2)).tostring("#.##").replace(',','.') } else { 0 }
               if($uniqueRecipentDomainsCnt -lt $rptTopNDD){
	                Write-Host  'uniqueRecipentDomains ' $s.Item(0)','$s.Item(1)','$inbundsize #for Inbound domains measure here sender is others and reciver ours domain
                    $uniqueRecipentDomainsCnt++
                }
	        }
  
            ## ADDING ROWS TO TABLE
            $recipncount=0
            ForEach ($Recipient in $MailOutboundDomain.keys){ 
	            $RecipientName = $Recipient 
                $recipncount++
		        $row = $Outbunddomainstab.NewRow() 
		        $row.Recipient = $RecipientName 
		        $row.Inbound = $MailOutboundDomain[$RecipientName].Inbound 
		        $row.InboundSize = ($MailOutboundDomain[$RecipientName].InboundSize)/1024
		        $Outbunddomainstab.Rows.Add($row)     
	        }
   
	        #"*******Top 10 Recipents Domains by Outbound items*******" 
	        $unqueOutdoms = $Outbunddomainstab | sort Inbound -Descending # | select -first 10  | ConvertTo-Csv -NoTypeInformation -Delimiter "," | % {$_ -replace '"',''}
            $uniqueSenderDomainsCnt = 0
            foreach($s in $unqueOutdoms){
                $outboundsize=if($s.Item(2) -gt 0){ ($s.Item(2)).tostring("#.##").replace(',','.') } else { 0 }
	            if($uniqueSenderDomainsCnt -lt $rptTopNDD){
                    Write-Host  'uniqueSenderDomains' $s.Item(0)','$s.Item(1)',' $outboundsize   ## for outbound domains measure dd and here we are getting domains where sender is ours and recevers in other
                    $uniqueSenderDomainsCnt++
                }
	        }
            Write-Host 'uniquesdominascount'  $MailOutboundDomain.Count '~'  $MailInboundDomain.count   
            Write-Host 'donewithMeasuresofdomain#'$domainname    
        }            
    }            
}
