读取文件夹内容并查找今天的lastwritetime,如果找到今天的lastwritetime的文件通过电子邮件发送它

时间:2014-12-16 18:27:39

标签: powershell

我有一个文件夹,只要作业失败就会向其写入日志,该文件夹也包含所有旧日志。目标是每天向用户发送一封电子邮件,并生成日志文件。如果找到日志,则发送附件中的文件,否则发送未找到的电子邮件说明文件。我把脚本放在下面,但问题是它读取所有文件,即使今天只有一个日志文件。

$TodaysDate = (Get-Date).DayOfYear
$LogPath    = "C:\Temp\Error"
$filename   = Get-ChildItem -Path "C:\temp\Error" 
foreach ($file in $LogPath) {
  $fileDate = ($file.LastWriteTime).DayOfYear

  if ($fileDate -eq $TodaysDate) {
    $fileName = $file.Name
  }
}
$LogFile       = $LogPath + $filename
$LogFileName   = $LogFile | ? {Test-Path $LogFile} | Get-ChildItem |
                   Where-Object { $_ -is [System.IO.FileInfo] }
$MessageBodyNA = "Email from task scheduler. No log file found" + $filename
$MessageBodyA  = "Email from task scheduler. File" + $LogFileName + 
                 " found and attached"
#
$FromAddress   = "test@gmail.com"
#
$ToAddress     = "test@gmail.com"
$Subject       = "Bad log"
# SMTP server name
$SMTPserver    = "smtp.test"
# check if attachment file exists if so email with attachment else without
# attachment
if ( $LogFileName | Where-Object { $_ -is [System.IO.FileInfo] }) {
  send-mailmessage -from $FromAddress -to $ToAddress -subject $Subject `
    -body $MessageBodyA -smtpServer $SMTPserver -Attachments $LogFileName
} else {
  send-mailmessage -from $FromAddress -to $ToAddress -subject $Subject `
    -body $MessageBodyNA  -smtpServer $SMTPserver
}

1 个答案:

答案 0 :(得分:0)

您确定文件的例程完全错综复杂。改变这个:

$TodaysDate = (Get-Date).DayOfYear
$LogPath    = "C:\Temp\Error"
$filename   = Get-ChildItem -Path "C:\temp\Error" 
foreach ($file in $LogPath) {
  $fileDate = ($file.LastWriteTime).DayOfYear

  if ($fileDate -eq $TodaysDate) {
    $fileName = $file.Name
  }
}
$LogFile       = $LogPath + $filename
$LogFileName   = $LogFile | ? {Test-Path $LogFile} | Get-ChildItem |
                   Where-Object { $_ -is [System.IO.FileInfo] }

进入这个:

$LogPath     = "C:\Temp\Error"
$LogFileName = Get-ChildItem $LogPath | ? {
                 -not $_.PSIsContainer -and
                 $_.LastWriteTime.Date -eq (Get-Date).Date
               }