none
Script to Find latest Modify date, and email alert if last modify is older than 4hrs or so RRS feed

  • Question

  • So, I want to monitor a directory, and get an alert if any file in the directory was not modified in the last, 4 hours or so.  

    I think I'm on the right track, but I'm missing some pieces here.  Any suggestions?

    Here's what I got so far:

    ::Set time and date to use later if needed
    set currentTime_Date=%time% %date%
    ::For loop to pull the last file (I can't seem to pull the last modify time/date with it... this is where I need a hand)
    FOR /F "delims=" %a IN ('DIR "*.*" /B /O:D') DO SET NewestFile=%a 

    ::Email latest file using blat
    blat.exe -to my@email.com -server server@domain.com -f from@email.com -subject "File Checker" -body "test" -attach %NewestFile% (Not sure if I can use the variable for my newest file here or not)


    Any suggestions?


    • Edited by JoeFri Friday, February 27, 2015 5:05 PM
    Friday, February 27, 2015 5:05 PM

Answers

  • Here.  Schedule this to run once an hour.

    $folder='C:\v1\temp'
    $Logfile = "C:\PicksheetMonitoring\WhileLoop.log"
    
    function logit($msg){
        $msg='' -f [datetime]::Now, $msg
        $msg|Out-File $logfile -append
    }
    logit 'Running check'
    if([datetime]::Now - (Get-Item $folder).LastWriteTime) -gt [timespan]'0:4:0:0'){
        Send-MailMessage -to "Picksheet Analysis <Picksheet_Analysis@domain.com>" -from "Picksheet Alerting <Picksheet_Alert@domain.com>" -subject "It's been at least 4 hours since last Automation run" -smtpserver "exch01.domain.com" ..
        logit 'alert sent'
    }else{
        logit 'all files good'
    }
    

    You do not want to run a scheduled task in a loop.  It defeats the purpose of a scheduled task.


    ¯\_(ツ)_/¯

    • Marked as answer by JoeFri Wednesday, March 25, 2015 12:21 PM
    Tuesday, March 24, 2015 8:54 PM
  • Upgraded to V4 PS, and same error with this script (Note you had the variables and first function doubled up)

    $folder='C:\v1\temp'
    $Logfile = "C:\PicksheetMonitoring\WhileLoop.log"
    
    function logit($msg){
        $msg='[{0}]{1}' -f [datetime]::Now, $msg
        $msg|Out-File $logfile -append
    }
    logit 'Running check'
    if([datetime]::Now - (Get-Item $folder).LastWriteTime -gt [timespan]'0:4:0:0'){
        Send-MailMessage -to "Picksheet Analysis <Picksheet_Analysis@domain.com>" -from "Picksheet Alerting <Picksheet_Alert@domain.com>" -subject "It's been at least 4 hours since last Automation run" -smtpserver "exch01.domain.com" ..
        logit 'alert sent'
    }else{
        logit 'all files good'
    }

    • Marked as answer by JoeFri Tuesday, March 31, 2015 12:44 PM
    Tuesday, March 31, 2015 1:19 AM

All replies

  • $folder='c:\myfolder'
    
    while($true){
        if(([datetime]::Now - (Get-Item $folder).LastWriteTime) -gt [timespan]'0:4:0:0'){
            Send-MailMessage -to -from -subject ..
            break
        }
    }


    ¯\_(ツ)_/¯



    • Edited by jrv Monday, March 16, 2015 4:06 PM
    Friday, February 27, 2015 6:05 PM
  • Hmm, this looks interesting.  Is this a powershell script?  I like just using the folder modify date, rather than searching for individual files within the folder, that could work...
    Wednesday, March 11, 2015 1:33 PM
  • Trying to run this I get a "missing statement block after if ( condition)." :4 char:60

    Wednesday, March 11, 2015 2:17 PM
  • Hmm, this looks interesting.  Is this a powershell script?  I like just using the folder modify date, rather than searching for individual files within the folder, that could work...
    The folder modified date will change if files or directories are added to or removed from the folder, but not if an existing file in the folder is updated.

    [string](0..33|%{[char][int](46+("686552495351636652556262185355647068516270555358646562655775 0645570").substring(($_*2),2))})-replace " "

    Wednesday, March 11, 2015 2:38 PM
    Moderator
  • correct, and every log entry is two new files.  So it should work in this case.  I haven't had time to look at this further, but last time I tried, I was still getting the error I listed above, missing statement block.
    Monday, March 16, 2015 3:53 PM
  • correct, and every log entry is two new files.  So it should work in this case.  I haven't had time to look at this further, but last time I tried, I was still getting the error I listed above, missing statement block.

    Sorry - missing a paren.

    $folder='c:\myfolder'
    
    while($true){
        if([datetime]::Now - (Get-Item $folder).LastWriteTime) -gt [timespan]'0:4:0:0'){
            Send-MailMessage -to -from -subject ..
            break
        }
    }


    ¯\_(ツ)_/¯

    Monday, March 16, 2015 4:06 PM
  • What's the easiest way to export the PowerShell window to a log when this runs?   

    I have it all setup with a scheduled task, but it doesn't seem to be working. (I had an incident today where it had been 6-7 hours since the folder was updated, and never received an email)

    Here's what I was trying:

    $folder='C:\v1\temp'
    $Logfile = "C:\PicksheetMonitoring\WhileLoop.log"

    while($true){
        if([datetime]::Now - (Get-Item $folder).LastWriteTime) -gt [timespan]'0:4:0:0'){
            Send-MailMessage -to "Picksheet Analysis <Picksheet_Analysis@domain.com>" -from "Picksheet Alerting <Picksheet_Alert@domain.com>" -subject "It's been at least 4 hours since last Automation run" -smtpserver "exch01.domain.com" ..
            break
        }
    }
    Function LogWrite
    {
       Param ([string]$logstring)

       Add-content $Logfile -value $logstring
    }

    Tuesday, March 24, 2015 6:19 PM
  • Here.  Schedule this to run once an hour.

    $folder='C:\v1\temp'
    $Logfile = "C:\PicksheetMonitoring\WhileLoop.log"
    
    function logit($msg){
        $msg='' -f [datetime]::Now, $msg
        $msg|Out-File $logfile -append
    }
    logit 'Running check'
    if([datetime]::Now - (Get-Item $folder).LastWriteTime) -gt [timespan]'0:4:0:0'){
        Send-MailMessage -to "Picksheet Analysis <Picksheet_Analysis@domain.com>" -from "Picksheet Alerting <Picksheet_Alert@domain.com>" -subject "It's been at least 4 hours since last Automation run" -smtpserver "exch01.domain.com" ..
        logit 'alert sent'
    }else{
        logit 'all files good'
    }
    

    You do not want to run a scheduled task in a loop.  It defeats the purpose of a scheduled task.


    ¯\_(ツ)_/¯

    • Marked as answer by JoeFri Wednesday, March 25, 2015 12:21 PM
    Tuesday, March 24, 2015 8:54 PM
  • Thanks again JRV!

    Sorry but... any idea why it continues to run just like the while loop did?  

    Also, a log file hasn't generated yet either.  

    :(


    Wednesday, March 25, 2015 12:29 PM
  • Sounds like you need to learn how to debug scheduled tasks.  Other than configuration there is no reason.


    ¯\_(ツ)_/¯

    Wednesday, March 25, 2015 12:31 PM
  • Typically when a scheduled task is stuck running, it's because the 'program' the task is  trying to run either froze, errored out, or is still actually running...  All the reasons I can think of are related to the 'program' not to anything in the scheduled task, unless the security options are set wrong...(which I've tried and tested)

    Also, if I run the script outside of a scheduled task, just from PowerShell, the log file isn't generated either, which tells me there's still something not quite right with the script.  Unless I'm running it wrong...  I'm saving it as a ps1 and testing by right-clicking and "Run with PowerShell"  

    am I missing something?


    • Edited by JoeFri Wednesday, March 25, 2015 1:01 PM
    Wednesday, March 25, 2015 12:47 PM
  • Sorry .

    Change this line:

        $msg='' -f [datetime]::Now, $msg

    To:

        $msg='[{0}]{1}' -f [datetime]::Now, $msg


    ¯\_(ツ)_/¯

    Wednesday, March 25, 2015 1:16 PM
  • You had other logic errors in your original.

    $folder='C:\v1\temp'
    $Logfile = "C:\temp\WhileLoop.log"
    
    function logit($msg){
        $msg='[{0}]{1}' -f [datetime]::Now, $msg
        $msg|Out-File $logfile -append
    }
    
    $folder='C:\v1\temp'
    $Logfile = "C:\PicksheetMonitoring\WhileLoop.log"
    
    function logit($msg){
        $msg='[{0}]{1}' -f [datetime]::Now, $msg
        $msg|Out-File $logfile -append
    }
    logit 'Running check'
    if([datetime]::Now - (Get-Item $folder).LastWriteTime -gt [timespan]'0:4:0:0'){
        Send-MailMessage -to "Picksheet Analysis <Picksheet_Analysis@domain.com>" -from "Picksheet Alerting <Picksheet_Alert@domain.com>" -subject "It's been at least 4 hours since last Automation run" -smtpserver "exch01.domain.com" ..
        logit 'alert sent'
    }else{
        logit 'all files good'
    }


    ¯\_(ツ)_/¯

    Wednesday, March 25, 2015 1:22 PM
  • We're closer!  

    Thanks for all your help so far JRV

    Log file is now generating, but all I get it:

    [3/25/2015 11:24:07 AM]Running check

    I get a "Cannot convert value "0:4:0:0" to type "System.TimeSpan" . Error: "Input string was not in correct format"  

    I'll look up some of the System.TimeSpan parameters to try to find the right one..

    Any idea's here?


    • Edited by JoeFri Wednesday, March 25, 2015 4:54 PM
    Wednesday, March 25, 2015 3:27 PM
  • jrv, do you know what this could be?  I'm not having any luck finding the correct params
    Thursday, March 26, 2015 12:18 PM
  • Wrong version of PowerShell?

    V1 doesn't understand that.


    ¯\_(ツ)_/¯

    Thursday, March 26, 2015 12:57 PM
  • V2 has issues too and requires this:

    [timespan]'4:0:0' # hh:mm:ss


    ¯\_(ツ)_/¯

    Thursday, March 26, 2015 1:00 PM
  • Thanks again for the quick response jrv,

    I did a get-host,

    I am on version 2.0,  is it worth upgrading? 

    If I stay with 2.0, the added code you just put in, does that need to be in any extra parenthesis or anything?  

    (I tested it and got this):

    Thanks again for all your help... sorry I'm such a PS dummy here...

    Thursday, March 26, 2015 2:56 PM
  • Upgraded to V4 PS, and same error with this script (Note you had the variables and first function doubled up)

    $folder='C:\v1\temp'
    $Logfile = "C:\PicksheetMonitoring\WhileLoop.log"
    
    function logit($msg){
        $msg='[{0}]{1}' -f [datetime]::Now, $msg
        $msg|Out-File $logfile -append
    }
    logit 'Running check'
    if([datetime]::Now - (Get-Item $folder).LastWriteTime -gt [timespan]'0:4:0:0'){
        Send-MailMessage -to "Picksheet Analysis <Picksheet_Analysis@domain.com>" -from "Picksheet Alerting <Picksheet_Alert@domain.com>" -subject "It's been at least 4 hours since last Automation run" -smtpserver "exch01.domain.com" ..
        logit 'alert sent'
    }else{
        logit 'all files good'
    }

    • Marked as answer by JoeFri Tuesday, March 31, 2015 12:44 PM
    Tuesday, March 31, 2015 1:19 AM
  • Works fine for me.  Maybe you are missing patches.


    ¯\_(ツ)_/¯

    Tuesday, March 31, 2015 4:40 AM
  • Thanks for the quick reply jrv,  here's what I got:

    Tuesday, March 31, 2015 12:38 PM
  • Nevermind!  

    I found a slight deviance from the original code,  it's working like a charm now! :)

    Thanks for all your help jrv, you rock!

    For future reference, Task Manager doesn't like calling PS scripts.  A quick bat file can be used to call the PS script, and then does not need to save credentials either (Change the YOURPOWERSHELLSCRIPT line for your script:

    @ECHO OFF

    SET ThisScriptsDirectory=%~dp0
    SET PowerShellScriptPath=%ThisScriptsDirectory%YOURPOWERSHELLSCRIPT.ps1
    PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%'";

    • Edited by JoeFri Tuesday, March 31, 2015 4:10 PM
    Tuesday, March 31, 2015 12:44 PM
  • Hey jrv,

    I may be getting a little greedy now, but I'm wondering if the datetime function can be used to bypass the email section of this script and only create the log entry for a specific timeframe. (ie after business hours, 5p-5a)

    Wednesday, April 1, 2015 12:07 PM
  • Task Scheduler loves calling PowerShell:

    Works every time.  Use any arguments you want.  Be careful with quoting.


    ¯\_(ツ)_/¯

    Thursday, April 2, 2015 5:42 PM
  • Hey jrv,

    I may be getting a little greedy now, but I'm wondering if the datetime function can be used to bypass the email section of this script and only create the log entry for a specific timeframe. (ie after business hours, 5p-5a)

    New question.  Start a new topic and describe clearly what you are asking. As stated it seems a bit odd.


    ¯\_(ツ)_/¯

    Thursday, April 2, 2015 5:43 PM
  • I tired it that way, and it still didn't work for some reason, I think it was related to how Task Scheduler was calling it :s

    Here's what I did and it works like a charm:

    Here's the Bat script:

    @ECHO OFF
    SET ThisScriptsDirectory=%~dp0
    SET PowerShellScriptPath=%ThisScriptsDirectory%Monitor.ps1
    PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& '%PowerShellScriptPath%'";

    Monday, April 6, 2015 5:10 PM
  • Never mind here, I was able to use Task Manager scheduling to have it run at better times, so I don't get too many emails at night, when the automation service isn't running.

    Thanks again for all your help!

    Monday, April 6, 2015 5:11 PM
  • Dear Joe :

    just seeking some advise , very new to PS so excuse my basic understanding .

    When I apply the script it always alerts , please advise in the script where it scans for the time the file has been idle

    $folder='C:temp\test.txt'
    $Logfile = "C:temp\testlog.txt"

    function logit($msg){
        $msg='[{0}]{1}' -f [datetime]::Now, $msg
        $msg|Out-File $logfile -append
    }
    logit 'Running check'
    if([datetime]::Now - (Get-Item $folder).LastWriteTime -gt [timespan]'0:0:0:10'){
        Send-MailMessage -to "xxx@xxxx.com" -from "xxx@xxxx.com" -subject "It's been at least x hours since last Automation run" -smtpserver "smtp.xxxxxx.local" ..
        logit 'alert sent'
    }else{
        logit 'all files good'
    }

    Tuesday, October 17, 2017 3:34 PM
  • Hey Sye, I've just kind of learn as I go with PowerShell, but I think you're asking why the script you listed triggers an email every time you run the script.

    But it looks like your "$Folder" variable is actually a file and has some syntax errors "C:temp" it should be "C:\temp"  - this is the folder you are checking the "Last modify time" on.  If this folder has been modified in less than 10 minutes, it won't trigger. (based on your "[timespan]'0:0:0:10'){")

    I hope that helps...


    Tuesday, October 17, 2017 8:24 PM
  • Please do not try to answer very old questions that have been marked as answered.  Also read all parts of the topic carefully.

    The problem was solved.


    \_(ツ)_/

    Wednesday, October 18, 2017 1:33 AM
  • Hey Sye, I've just kind of learn as I go with PowerShell, but I think you're asking why the script you listed triggers an email every time you run the script.

    But it looks like your "$Folder" variable is actually a file and has some syntax errors "C:temp" it should be "C:\temp"  - this is the folder you are checking the "Last modify time" on.  If this folder has been modified in less than 10 minutes, it won't trigger. (based on your "[timespan]'0:0:0:10'){")

    I hope that helps...



    Please open a new question for your question.

    \_(ツ)_/

    Wednesday, October 18, 2017 1:39 AM
  • This isn't a question, this is an answer to Syedmh16 's question
    Wednesday, October 18, 2017 12:03 PM
  • This isn't a question, this is an answer to Syedmh16 's question

    The topic is marked as answered. The thread is over two years old.

    \_(ツ)_/

    Wednesday, October 18, 2017 2:39 PM
  • and  Syedmh16 asked a question about a thread that is over two years old, so I answered it.
    Wednesday, October 18, 2017 3:10 PM
  • Ok. Sorry, I didn't quite catch that.


    \_(ツ)_/

    Wednesday, October 18, 2017 3:14 PM
  • no worries
    Wednesday, October 18, 2017 3:17 PM
  • can you guide me i want email in any case and want what ever the last modify date in subject or body
    Wednesday, October 21, 2020 7:50 AM
  • PLEASE do not kidnap old threads from other users. If you have a question related to this one you should create a new thread for yourself and place a link to this one in your question.

    Thanks in advance

     

    Live long and prosper!

    (79,108,97,102|%{[char]$_})-join''

    Wednesday, October 21, 2020 8:13 AM