Check the most recent file delivery was in the last 6 hours

Hi, I have a script to check for the arrival of daily sales file from vendor and we receive these files a little after midnight around 12:30 am. Of late the arrival of files have been irregular hence I am doing a file check right before the processing of files happen. The job is scheduled to run daily at 6:00 am. I am use the below logic to do the file check.

# GET THE MOST RECENT FILE 
$File = Get-ChildItem -Path "C:\Sales\" -Filter "*.csv" | Sort-Object LastWriteTime -Descending | Select-Object -First 1
Write-Output "Recent CSV File: $($File.FullName)"

# CHECK FOR THE MOST RECENT FILE 
if(-NOT ($File.LastWriteTime.Date -lt (Get-Date).AddDays(0).AddHours(-6)))
{
#Send e-mail notification
Send-MailMessage -From $From -to $To -Subject $Subject -BodyAsHtml $Body -SmtpServer $SMTPServer 
}
else
{
#Process file
}

I am not sure if this is the right approach. Please guide me.

Thank you in advance.

venkatesh

When you post code, error messages, sample data or console output format it as code, please.
In the “Text” view you can use the code tags “PRE”, in the “Visual” view you can use the format template “Preformatted”. You can go back edit your post and fix the formatting - you don’t have to create a new one.
Thanks in advance.

If I got it right you just have to check if the file is from today. This would be something like this:

$File.LastWriteTime.Date -eq (Get-Date).Date

BTW: You can omit the method .AddDays(0) when you do not want to add days anyway.

Hi, Thanks for your response. I apologize for the poor formatting. I am new to this forums and could not find the code in Format. The problem is I cannot rely on date as they arrive at different times. Some cases could be before midnight as well. So I am depending on timestamp. When I send the e-mail notification to the vendor I will have the job run time so they will know if they were either too early or too late. For instance I had some files after the 6:00 am job run.

Regards.

OK, But then you should remove the .Date sub expression as it cuts of the time from your timestamp leaving only the date.

So your code should look something like this I think:

$File = 
    Get-ChildItem -Path 'C:\Sales' -Filter '*.csv' | 
        Sort-Object -Property LastWriteTime -Descending | 
            Select-Object -First 1
if (-NOT ($File.LastWriteTime -gt (Get-Date).AddHours(-6))) {
    $SendMailMessageParams = @{
        From       = $From
        to         = $To
        Subject    = $Subject
        BodyAsHtml = $Body
        SmtpServer = $SMTPServer
    }
    Send-MailMessage @SendMailMessageParams
}
else {
    #Process file
}

This will check if the file is newer than 6 hours.

Thanks very much for pointing me in the right direction. I will try it out and keep you posted.

Regards