Skip to main content

Alert if file missing using Powershell

The following Powershell script can be used to send an email alert when a file is missing from a folder or it is the same file from a previous check:

$path_mask = "yourfile_*.txt"
$previous_file_store = "lastfileread.txt"
$script_name = "File Check"



###### Functions ##########
Function EMailLog($subject, $message)
{
   $emailTo = "juanito@yourserver.com"
   $emailFrom = "alert@yourserver.com"
   $smtpserver="smtp.yourserver.com"   
   $smtp=new-object Net.Mail.SmtpClient($smtpServer)
   $smtp.Send($emailFrom, $emailTo, $subject, $message)
}



Try
{
   #get files that match the mask
   $curr_file = dir $path_mask |  select name

   if ($curr_file.count -gt 0)
   {
       #file found
       #check if the file is different from the previous file read
       $previous_file = Get-Content $previous_file_store
       $curr_file_name = $curr_file.Item(0).Name

       if ($previous_file.trim() -eq  $curr_file_name.trim())
       {
           $msg = "Found same file as previous check: $previous_file and $curr_file_name"
           $msg
           EMailLog "$script_name Error" $msg
       }
       else
       {
           #different file, record its name for comparing in the next run
           $curr_file.Item(0).Name | out-file -filepath $previous_file_store
       }

   }
   else
   {
       $msg = "$path_mask Not found"
       $msg
       EMailLog "$script_name Error" $msg
   }
}
Catch [system.exception]
{
   "Caught a system exception "
   $error
   $error.Exception | EMailLog  "$script_name System error" $_
   
}


Comments