Solved

Poweshell Script to save file to certain network location and email it on a schedule

Posted on 2011-03-15
4
746 Views
Last Modified: 2012-08-14
So I have a script that someone else created, and I want to modify the script so that it save the file that it creates to a certain network folder and then also emails the file to a recipient on a daily (m-f) schedule.



#mjolinor
#02/24/2011

#requires -version 2.0

$today = get-date
$rundate = $($today.adddays(-1)).toshortdatestring()

$outfile_date = ([datetime]$rundate).tostring("yyyy_MM_dd")
$outfile = "email_stats_" + $outfile_date + ".csv"

$dl_stat_file = "DL_stats.csv"

$accepted_domains = Get-AcceptedDomain |% {$_.domainname.domain}
[regex]$dom_rgx = "`(?i)(?:" + (($accepted_domains |% {"@" + [regex]::escape($_)}) -join "|") + ")$"

$mbx_servers = Get-ExchangeServer |? {$_.serverrole -match "Mailbox"}|% {$_.fqdn}
[regex]$mbx_rgx = "`(?i)(?:" + (($mbx_servers |% {"@" + [regex]::escape($_)}) -join "|") + ")\>$"

$msgid_rgx = "^\<.+@.+\..+\>$"

$hts = get-exchangeserver |? {$_.serverrole -match "hubtransport"} |% {$_.name}

$exch_addrs = @{}

$msgrec = @{}
$bytesrec = @{}

$msgrec_exch = @{}
$bytesrec_exch = @{}

$msgrec_smtpext = @{}
$bytesrec_smtpext = @{}

$total_msgsent = @{}
$total_bytessent = @{}
$unique_msgsent = @{}
$unique_bytessent = @{}

$total_msgsent_exch = @{}
$total_bytessent_exch = @{}
$unique_msgsent_exch = @{}
$unique_bytessent_exch = @{}

$total_msgsent_smtpext = @{}
$total_bytessent_smtpext = @{}
$unique_msgsent_smtpext=@{}
$unique_bytessent_smtpext = @{}

$dl = @{}


$obj_table = {
@"
Date = $rundate
User = $($address.split("@")[0])
Domain = $($address.split("@")[1])
Sent Total = $(0 + $total_msgsent[$address])
Sent MB Total = $("{0:F2}" -f $($total_bytessent[$address]/1mb))
Received Total = $(0 + $msgrec[$address])
Received MB Total = $("{0:F2}" -f $($bytesrec[$address]/1mb))
Sent Internal = $(0 + $total_msgsent_exch[$address])
Sent Internal MB = $("{0:F2}" -f $($total_bytessent_exch[$address]/1mb))
Sent External = $(0 + $total_msgsent_smtpext[$address])
Sent External MB = $("{0:F2}" -f $($total_bytessent_smtpext[$address]/1mb))
Received Internal = $(0 + $msgrec_exch[$address])
Received Internal MB = $("{0:F2}" -f $($bytesrec_exch[$address]/1mb))
Received External = $(0 + $msgrec_smtpext[$address])
Received External MB = $("{0:F2}" -f $($bytesrec_smtpext[$address]/1mb))
Sent Unique Total = $(0 + $unique_msgsent[$address])
Sent Unique MB Total = $("{0:F2}" -f $($unique_bytessent[$address]/1mb))
Sent Internal Unique  = $(0 + $unique_msgsent_exch[$address]) 
Sent Internal Unique MB = $("{0:F2}" -f $($unique_bytessent_exch[$address]/1mb))
Sent External  Unique = $(0 + $unique_msgsent_smtpext[$address])
Sent External Unique MB = $("{0:F2}" -f $($unique_bytessent_smtpext[$address]/1mb))
"@
}

$props = $obj_table.ToString().Split("`n")|% {if ($_ -match "(.+)="){$matches[1].trim()}}

$stat_recs = @()

function time_pipeline {
param ($increment  = 1000)
begin{$i=0;$timer = [diagnostics.stopwatch]::startnew()}
process {
    $i++
    if (!($i % $increment)){Write-host “`rProcessed $i in $($timer.elapsed.totalseconds) seconds” -nonewline}
    $_
    }
end {
	write-host “`rProcessed $i log records in $($timer.elapsed.totalseconds) seconds”
	Write-Host "   Average rate: $([int]($i/$timer.elapsed.totalseconds)) log recs/sec."
	}
}

foreach ($ht in $hts){

	Write-Host "`nStarted processing $ht"

	get-messagetrackinglog -Server $ht -Start "$rundate" -End "$rundate 11:59:59 PM" -resultsize unlimited |
	time_pipeline |%{
	
	
	if ($_.eventid -eq "DELIVER" -and $_.source -eq "STOREDRIVER"){
	
		if ($_.messageid -match $mbx_rgx -and $_.sender -match $dom_rgx) {
			
			$total_msgsent[$_.sender] += $_.recipientcount
			$total_bytessent[$_.sender] += ($_.recipientcount * $_.totalbytes)
			$total_msgsent_exch[$_.sender] += $_.recipientcount
			$total_bytessent_exch[$_.sender] += ($_.totalbytes * $_.recipientcount)
		
			foreach ($rcpt in $_.recipients){
			$exch_addrs[$rcpt] ++
			$msgrec[$rcpt] ++
			$bytesrec[$rcpt] += $_.totalbytes
			$msgrec_exch[$rcpt] ++
			$bytesrec_exch[$rcpt] += $_.totalbytes
			}
			
		}
		
		else {
			if ($_messageid -match $messageid_rgx){
					foreach ($rcpt in $_.recipients){
						$msgrec[$rcpt] ++
						$bytesrec[$rcpt] += $_.totalbytes
						$msgrec_smtpext[$rcpt] ++
						$bytesrec_smtpext[$rcpt] += $_.totalbytes
					}
				}
		
			}
				
	}
	
	
	if ($_.eventid -eq "RECEIVE" -and $_.source -eq "STOREDRIVER"){
		$exch_addrs[$_.sender] ++
		$unique_msgsent[$_.sender] ++
		$unique_bytessent[$_.sender] += $_.totalbytes
		
			if ($_.recipients -match $dom_rgx){
				$unique_msgsent_exch[$_.sender] ++
				$unique_bytessent_exch[$_.sender] += $_.totalbytes
				}

			if ($_.recipients -notmatch $dom_rgx){
				$ext_count = ($_.recipients -notmatch $dom_rgx).count
				$unique_msgsent_smtpext[$_.sender] ++
				$unique_bytessent_smtpext[$_.sender] += $_.totalbytes
			    $total_msgsent[$_.sender] += $ext_count
				$total_bytessent[$_.sender] += ($ext_count * $_.totalbytes)
				$total_msgsent_smtpext[$_.sender] += $ext_count
 			    $total_bytessent_smtpext[$_.sender] += ($ext_count * $_.totalbytes)
				}
                               
			
		}
		
	if ($_.eventid -eq "expand"){
		$dl[$_.relatedrecipientaddress] ++
		}
	}	 
	
}

foreach ($address in $exch_addrs.keys){

$stat_rec = (new-object psobject -property (ConvertFrom-StringData (&$obj_table)))
$stat_recs += $stat_rec | select $props
}

$stat_recs | export-csv $outfile -notype 

if (Test-Path $dl_stat_file){
	$DL_stats = Import-Csv $dl_stat_file
	$dl_list = $dl_stats |% {$_.address}
	}
	
else {
	$dl_list = @()
	$DL_stats = @()
	}


$DL_stats |% {
	if ($dl[$_.address]){
		if ([datetime]$_.lastused -le [datetime]$rundate){ 
			$_.used = [int]$_.used + [int]$dl[$_.address]
			$_.lastused = $rundate
			}
		}
}
	
$dl.keys |% {
	if ($dl_list -notcontains $_){
		$new_rec = "" | select Address,Used,Since,LastUsed
		$new_rec.address = $_
		$new_rec.used = $dl[$_]
		$new_rec.Since = $rundate
		$new_rec.lastused = $rundate
		$dl_stats += @($new_rec)
	}
}

$dl_stats | Export-Csv $dl_stat_file -NoTypeInformation -force


Write-Host "`nRun time was $(((get-date) - $today).totalseconds) seconds."
Write-Host "Email stats file is $outfile"
Write-Host "DL usage stats file is $dl_stat_file"


#Contact information
#[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

Open in new window

0
Comment
Question by:Travis Hahn
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
4 Comments
 
LVL 12

Expert Comment

by:prashanthd
ID: 35147383
Is it the email stats file which has to be stored and emailed?
0
 

Author Comment

by:Travis Hahn
ID: 35147951
yes - I would like it to be created on a network share and emailed.  I
0
 
LVL 12

Accepted Solution

by:
prashanthd earned 500 total points
ID: 35149472
Try the following, set the network path and email details

#mjolinor
#02/24/2011

#requires -version 2.0

$network_path="" #example \\servername\c$\foldername\" - ensure administrative share path and "\" after foldername
$FromAddress = "" # from email address
$ToAddress = "" # to email address
$MessageSubject = "Email Stats Report" # Email Subject
$MessageBody = "Attached is Report" # Email Body
$SendingServer = ""  #needs the smtp server name throrugh mail will be sent

$today = get-date
$rundate = $($today.adddays(-1)).toshortdatestring()

$outfile_date = ([datetime]$rundate).tostring("yyyy_MM_dd")
$outfile = "email_stats_" + $outfile_date + ".csv"
$outfile = $network_path + $outfile

$dl_stat_file = "DL_stats.csv"

$accepted_domains = Get-AcceptedDomain |% {$_.domainname.domain}
[regex]$dom_rgx = "`(?i)(?:" + (($accepted_domains |% {"@" + [regex]::escape($_)}) -join "|") + ")$"

$mbx_servers = Get-ExchangeServer |? {$_.serverrole -match "Mailbox"}|% {$_.fqdn}
[regex]$mbx_rgx = "`(?i)(?:" + (($mbx_servers |% {"@" + [regex]::escape($_)}) -join "|") + ")\>$"

$msgid_rgx = "^\<.+@.+\..+\>$"

$hts = get-exchangeserver |? {$_.serverrole -match "hubtransport"} |% {$_.name}

$exch_addrs = @{}

$msgrec = @{}
$bytesrec = @{}

$msgrec_exch = @{}
$bytesrec_exch = @{}

$msgrec_smtpext = @{}
$bytesrec_smtpext = @{}

$total_msgsent = @{}
$total_bytessent = @{}
$unique_msgsent = @{}
$unique_bytessent = @{}

$total_msgsent_exch = @{}
$total_bytessent_exch = @{}
$unique_msgsent_exch = @{}
$unique_bytessent_exch = @{}

$total_msgsent_smtpext = @{}
$total_bytessent_smtpext = @{}
$unique_msgsent_smtpext=@{}
$unique_bytessent_smtpext = @{}

$dl = @{}


$obj_table = {
@"
Date = $rundate
User = $($address.split("@")[0])
Domain = $($address.split("@")[1])
Sent Total = $(0 + $total_msgsent[$address])
Sent MB Total = $("{0:F2}" -f $($total_bytessent[$address]/1mb))
Received Total = $(0 + $msgrec[$address])
Received MB Total = $("{0:F2}" -f $($bytesrec[$address]/1mb))
Sent Internal = $(0 + $total_msgsent_exch[$address])
Sent Internal MB = $("{0:F2}" -f $($total_bytessent_exch[$address]/1mb))
Sent External = $(0 + $total_msgsent_smtpext[$address])
Sent External MB = $("{0:F2}" -f $($total_bytessent_smtpext[$address]/1mb))
Received Internal = $(0 + $msgrec_exch[$address])
Received Internal MB = $("{0:F2}" -f $($bytesrec_exch[$address]/1mb))
Received External = $(0 + $msgrec_smtpext[$address])
Received External MB = $("{0:F2}" -f $($bytesrec_smtpext[$address]/1mb))
Sent Unique Total = $(0 + $unique_msgsent[$address])
Sent Unique MB Total = $("{0:F2}" -f $($unique_bytessent[$address]/1mb))
Sent Internal Unique  = $(0 + $unique_msgsent_exch[$address])
Sent Internal Unique MB = $("{0:F2}" -f $($unique_bytessent_exch[$address]/1mb))
Sent External  Unique = $(0 + $unique_msgsent_smtpext[$address])
Sent External Unique MB = $("{0:F2}" -f $($unique_bytessent_smtpext[$address]/1mb))
"@
}

$props = $obj_table.ToString().Split("`n")|% {if ($_ -match "(.+)="){$matches[1].trim()}}

$stat_recs = @()

function time_pipeline {
param ($increment  = 1000)
begin{$i=0;$timer = [diagnostics.stopwatch]::startnew()}
process {
    $i++
    if (!($i % $increment)){Write-host “`rProcessed $i in $($timer.elapsed.totalseconds) seconds” -nonewline}
    $_
    }
end {
      write-host “`rProcessed $i log records in $($timer.elapsed.totalseconds) seconds”
      Write-Host "   Average rate: $([int]($i/$timer.elapsed.totalseconds)) log recs/sec."
      }
}

foreach ($ht in $hts){

      Write-Host "`nStarted processing $ht"

      get-messagetrackinglog -Server $ht -Start "$rundate" -End "$rundate 11:59:59 PM" -resultsize unlimited |
      time_pipeline |%{
      
      
      if ($_.eventid -eq "DELIVER" -and $_.source -eq "STOREDRIVER"){
      
            if ($_.messageid -match $mbx_rgx -and $_.sender -match $dom_rgx) {
                  
                  $total_msgsent[$_.sender] += $_.recipientcount
                  $total_bytessent[$_.sender] += ($_.recipientcount * $_.totalbytes)
                  $total_msgsent_exch[$_.sender] += $_.recipientcount
                  $total_bytessent_exch[$_.sender] += ($_.totalbytes * $_.recipientcount)
            
                  foreach ($rcpt in $_.recipients){
                  $exch_addrs[$rcpt] ++
                  $msgrec[$rcpt] ++
                  $bytesrec[$rcpt] += $_.totalbytes
                  $msgrec_exch[$rcpt] ++
                  $bytesrec_exch[$rcpt] += $_.totalbytes
                  }
                  
            }
            
            else {
                  if ($_messageid -match $messageid_rgx){
                              foreach ($rcpt in $_.recipients){
                                    $msgrec[$rcpt] ++
                                    $bytesrec[$rcpt] += $_.totalbytes
                                    $msgrec_smtpext[$rcpt] ++
                                    $bytesrec_smtpext[$rcpt] += $_.totalbytes
                              }
                        }
            
                  }
                        
      }
      
      
      if ($_.eventid -eq "RECEIVE" -and $_.source -eq "STOREDRIVER"){
            $exch_addrs[$_.sender] ++
            $unique_msgsent[$_.sender] ++
            $unique_bytessent[$_.sender] += $_.totalbytes
            
                  if ($_.recipients -match $dom_rgx){
                        $unique_msgsent_exch[$_.sender] ++
                        $unique_bytessent_exch[$_.sender] += $_.totalbytes
                        }

                  if ($_.recipients -notmatch $dom_rgx){
                        $ext_count = ($_.recipients -notmatch $dom_rgx).count
                        $unique_msgsent_smtpext[$_.sender] ++
                        $unique_bytessent_smtpext[$_.sender] += $_.totalbytes
                      $total_msgsent[$_.sender] += $ext_count
                        $total_bytessent[$_.sender] += ($ext_count * $_.totalbytes)
                        $total_msgsent_smtpext[$_.sender] += $ext_count
                       $total_bytessent_smtpext[$_.sender] += ($ext_count * $_.totalbytes)
                        }
            }
            
      if ($_.eventid -eq "expand"){
            $dl[$_.relatedrecipientaddress] ++
            }
      }       
      
}

foreach ($address in $exch_addrs.keys){

$stat_rec = (new-object psobject -property (ConvertFrom-StringData (&$obj_table)))
$stat_recs += $stat_rec | select $props
}

$stat_recs | export-csv $outfile -notype

if (Test-Path $dl_stat_file){
      $DL_stats = Import-Csv $dl_stat_file
      $dl_list = $dl_stats |% {$_.address}
      }
      
else {
      $dl_list = @()
      $DL_stats = @()
      }


$DL_stats |% {
      if ($dl[$_.address]){
            if ([datetime]$_.lastused -le [datetime]$rundate){
                  $_.used = [int]$_.used + [int]$dl[$_.address]
                  $_.lastused = $rundate
                  }
            }
}
      
$dl.keys |% {
      if ($dl_list -notcontains $_){
            $new_rec = "" | select Address,Used,Since,LastUsed
            $new_rec.address = $_
            $new_rec.used = $dl[$_]
            $new_rec.Since = $rundate
            $new_rec.lastused = $rundate
            $dl_stats += @($new_rec)
      }
}

$dl_stats | Export-Csv $dl_stat_file -NoTypeInformation -force


Write-Host "`nRun time was $(((get-date) - $today).totalseconds) seconds."
Write-Host "Email stats file is $outfile"
Write-Host "DL usage stats file is $dl_stat_file"


#########################Send Mail################################

$SMTPMessage = New-Object System.Net.Mail.MailMessage $FromAddress, $ToAddress, $MessageSubject, $MessageBody

$Attachment = New-Object Net.Mail.Attachment($outfile)

$SMTPMessage.Attachments.Add($Attachment)

$SMTPClient = New-Object System.Net.Mail.SMTPClient

$SmtpClient.host = $SendingServer

$SMTPClient.Send($SMTPMessage)

#############################################################################

#Contact information
#[string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "
0
 

Author Closing Comment

by:Travis Hahn
ID: 35149717
Thanks for the help
0

Featured Post

Free learning courses: Active Directory Deep Dive

Get a firm grasp on your IT environment when you learn Active Directory best practices with Veeam! Watch all, or choose any amount, of this three-part webinar series to improve your skills. From the basics to virtualization and backup, we got you covered.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Auditing domain password hashes is a commonly overlooked but critical requirement to ensuring secure passwords practices are followed. Methods exist to extract hashes directly for a live domain however this article describes a process to extract u…
I was prompted to write this article after the recent World-Wide Ransomware outbreak. For years now, System Administrators around the world have used the excuse of "Waiting a Bit" before applying Security Patch Updates. This type of reasoning to me …
This Micro Tutorial hows how you can integrate  Mac OSX to a Windows Active Directory Domain. Apple has made it easy to allow users to bind their macs to a windows domain with relative ease. The following video show how to bind OSX Mavericks to …
A short tutorial showing how to set up an email signature in Outlook on the Web (previously known as OWA). For free email signatures designs, visit https://www.mail-signatures.com/articles/signature-templates/?sts=6651 If you want to manage em…
Suggested Courses

617 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question