Advertisement
upz

Check Existing files, and send mail

upz
Jul 10th, 2018
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. $filePath = "C:\test"
  2. $logPath = "C:\test\file.csv"
  3. $log
  4.  
  5. #Test if log exist, if exist import
  6. if (Test-Path -LiteralPath $logPath) {
  7.     $log = Import-Csv -LiteralPath $logPath -Delimiter ';'
  8. } else {
  9.     $log = $null
  10. }
  11.  
  12. $fileList = [System.Collections.Generic.List[PsObject]]::new()
  13. $files = Get-ChildItem -LiteralPath $filePath -Recurse -File | where {$_.CreationTime -gt (Get-Date).AddHours(-2)}
  14.  
  15. # Check if files are allready logged, else add to log
  16. foreach ($file in $files) {
  17.    
  18.     $hash = [ordered]@{
  19.         'dateScanned' = Get-Date
  20.         'name' = $file.Name
  21.         'fullName' = $file.FullName
  22.         'identifier' = "$($file.CreationTime.ToString("yyyyMMddhhmmss"))$($file.Name.Replace(' ',''))"
  23.     }
  24.     $obj = New-Object -TypeName PsObject -Property $hash
  25.  
  26.     if ($log.identifier -notcontains $obj.identifier) {
  27.         $fileList.Add($obj)
  28.     }    
  29. }
  30.  
  31. # send mail if there are new files, otherwise don't
  32. if ($fileList.count -ne 0) {
  33.    
  34.     $body = "Following files older than 2 hours have just been logged to $logPath`n"
  35.     $fileList.fullname | foreach {$body += "`n$_"}
  36.  
  37.     #Fill in your own mail info
  38.     $mailProperties = [ordered]@{
  39.         From =
  40.         Body = $body
  41.         SmtpServer =
  42.         Port =
  43.         To =
  44.         Subject =
  45.         Encoding =
  46.     }
  47.     Send-MailMessage -BodyAsHtml -UseSsl @mailProperties
  48. }
  49.  
  50. $fileList | Export-Csv -Path $logPath -Encoding UTF8 -Delimiter ';' -NoTypeInformation -Append
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement