PowerShell: Check for Existence of File and Send Email If File Does Not Exist

Wednesday, March 28, 2012
by jsalvo

I created a PowerShell script that runs as the first step in a SQL Server Agent Job.  The script checks for the existence of some files and sends an email and throws an exception to terminate the job if any of the files do not exist.  An example of the code is included below.


#File Locations
$file1 = "file://yourfilesharefile1.txt"
$file2 = "file://yourfilesharefile2.txt"

#Check for Existence of Files  
$file1Exists = Test-Path $file1

$file2Exists = Test-Path $file2

#Email Settings  
$emailFrom = "EmailFromAddress@yourdomain.com"  
$emailTo = "EmailToAddress@yourdomain.com" 
$subject = "Missing Files"
$body = "The following files are missing:\`r\`n"
$smtpServer = "123.45.67.890"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)

If ($file1Exists -and $file2Exists)  
{
  #Do Nothing  
}  
Else   
{
  #Generate Text for Email Body  
  If (-not $file1Exists) {  
    $body += "\`r\`n" + $file1 + " ."
  }  

  If (-not $file2Exists) {  
    $body += "\`r\`n" + $file2 + " ."
  }
  
  #Send Email  
  $smtp.Send($emailFrom, $emailTo, $subject, $body)

  #Throw Exception to Terminate Job  
  throw "Missing Files"

}

Comments

comments powered by Disqus