Pages

1/09/2013

Some code playing around with sending mail with an attachment from a powershell script. Also launching a packet capture from another process so I can asynchronously repeat a test while doing a capture. -> Although I was able to execute an external command that included variables (to build the command line with a custom value for delay and output file) I was not able to start a job to do that same thing. I resorted to creating a custom batch file for this script and defining tshark duration and output file in that BAT file. -- not as flexible as I was trying to be.

#INSTANCE 1 
#  - Capture command:  C:\WORK\CAP1.BAT
#  - Output file:  CAP1OUT.CAP

$temp = "c:\work"
$test = "\\fs05\users\admin\test"
$threshold = 10
$SmtpServer = "mail.usa.domain.com"
$emailfrom = "no-reply-monitor@domain.com)"
$emailto = "administrator@domain.com"
$emailsubject = "folder count monitor output"
$emailbody = "Folder:  $test contains less than $threshold items"
$emailattachment="c:\temp\file.txt"
$emailfrom = ""
$emailto = ""
$emailsubject = "Monitoring Output"  

function send_email {
 $mailmessage = New-Object system.net.mail.mailmessage 
 $mailmessage.from = ($emailfrom) 
 $mailmessage.To.add($emailto)
 $mailmessage.Subject = $emailsubject
 $mailmessage.Body = $emailbody
 $attachment = New-Object System.Net.Mail.Attachment($emailattachment, 'text/plain')
 $mailmessage.Attachments.Add($attachment)
 #$mailmessage.IsBodyHTML = $true
 $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)  
 #$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("$SMTPAuthUsername", "$SMTPAuthPassword")
 $SMTPClient.Send($mailmessage)
}#end-function

if ((Get-ChildItem $test).Count -lt $threshold){
 "capturing for 30 s"
 ####################################################
 #     CAPTURE COMMAND
   $job = start-job {&cmd "/c","C:\WORK\CAP1.BAT"}
 ####################################################
 start-sleep 10
 "Testing Folder $test"
  Get-ChildItem $test | out-null
 "waiting 30 s"
  Start-Sleep 30
 wait-job $job
 remove-job $job
 "sending CAP file to $emailto"
 ####################################################
 #     OUTPUT FILE
  $emailattachment = "c:\work\cap1out.cap"
 ####################################################
  send_email 
}

No comments: