Categories
PowerShell Scripting

PowerShell Check File Modified Time

Script to check is a specific file exists and its modified time is less than 1 day in the past. This script uses some custum functions from a imported module.

# Import DBA modules...
Import-Module 'D:\Path\To\DefaultFunctionsModule.psm1'

# Global config settings...
[string]$sSubject1 = "SBO:CheckLogFiles Errors Found..."
[string]$sSMTPServer1 = "smtp.example.com"
[string]$sToAddress1 = "mail@example.com"
[string]$sEventLogSource = "{eventlogsource}"

# Functions en Procedures...
function fnGetFileModTime([string]$sFileName) {
  $vFileInfo = get-childitem $sFileName
  return $vFileInfo.lastwritetime 
}

# Start Main script...
if ((Test-Path $args[0]) -and ($args[1])) {
  # Request file modified time...
  [datetime]$dFileModTime = fnGetFileModTime("$($args[0])")
  # Alert if file modified time is older than 1 day...
  if ((Get-date).AddDays(-1) -gt $dFileModTime) {
  $sMessage1 = "ERROR: File modified time is older than 1 day...`r`n`r`nFilename: " + $args[0] + "`r`nService: " + $args[1]
  fnWriteEventLog -sNode (fnGetFQDN) -sMessage $sMessage1
  fnSendMail -sSMTPSrvrName $sSMTPServer1 -sFrom (fnGetFQDN -swIsEmail) -sTo $sToAddress1 -sSubject $sSubject1 -sBody $sMessage1
  }
} else {
  if (($args[1])) {
    # Alert if file does not exist...
    $sMessage1 = "ERROR: File does not exist...`r`n`r`nFilename: " + $args[0] + "`r`nService: " + $args[1]
    fnWriteEventLog -sNode (fnGetFQDN) -sMessage $sMessage1
    fnSendMail -sSMTPSrvrName $sSMTPServer1 -sFrom (fnGetFQDN -swIsEmail) -sTo $sToAddress1 -sSubject $sSubject1 -sBody $sMessage1
  } else {
      $sMessage1 = "ERROR: Missing argument... [CheckModTime.ps1 `"c:\path\to\file`" `"service`"]`r`n`r`nFilename: " + $args[0]  + "`r`nService: " + $args[1]    
      echo $sMessage1
  }
}